feat: updates

This commit is contained in:
2025-03-29 00:04:25 +08:00
parent 6d3298549e
commit a6bff6d31c
36 changed files with 115 additions and 137 deletions

View File

@@ -4,7 +4,7 @@ use clap::{App, Arg, ArgMatches, SubCommand};
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use crate::ecdsautil::EcdsaAlgorithm; use crate::ecdsautil::EcdsaAlgorithm;
use crate::{argsutil, cmdutil, ecdsautil}; use crate::{argsutil, cmdutil, ecdsautil, util};
pub struct CommandImpl; pub struct CommandImpl;
@@ -70,7 +70,7 @@ impl Command for CommandImpl {
} }
if json_output { if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} }
Ok(None) Ok(None)
} }

View File

@@ -2,7 +2,7 @@ use clap::{App, Arg, ArgMatches, SubCommand};
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use std::collections::BTreeMap; use std::collections::BTreeMap;
use crate::{cmdutil, hmacutil}; use crate::{cmdutil, hmacutil, util};
pub struct CommandImpl; pub struct CommandImpl;
@@ -32,10 +32,8 @@ impl Command for CommandImpl {
if json_output { if json_output {
let mut json = BTreeMap::<&'_ str, String>::new(); let mut json = BTreeMap::<&'_ str, String>::new();
json.insert("plaintext", plaintext); json.insert("plaintext", plaintext);
println!(
"{}", util::print_pretty_json(&json);
serde_json::to_string_pretty(&json).expect("Convert to JSON failed!")
);
} else { } else {
success!("Plaintext: {}", plaintext); success!("Plaintext: {}", plaintext);
} }

View File

@@ -2,7 +2,7 @@ use clap::{App, Arg, ArgMatches, SubCommand};
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use std::collections::BTreeMap; use std::collections::BTreeMap;
use crate::{cmdutil, hmacutil}; use crate::{cmdutil, hmacutil, util};
pub struct CommandImpl; pub struct CommandImpl;
@@ -32,10 +32,8 @@ impl Command for CommandImpl {
if json_output { if json_output {
let mut json = BTreeMap::<&'_ str, String>::new(); let mut json = BTreeMap::<&'_ str, String>::new();
json.insert("ciphertext", hmac_encrypt_ciphertext); json.insert("ciphertext", hmac_encrypt_ciphertext);
println!(
"{}", util::print_pretty_json(&json);
serde_json::to_string_pretty(&json).expect("Convert to JSON failed!")
);
} else { } else {
success!("HMAC encrypt ciphertext: {}", hmac_encrypt_ciphertext); success!("HMAC encrypt ciphertext: {}", hmac_encrypt_ciphertext);
} }

View File

@@ -1,5 +1,5 @@
use crate::keychain::{KeychainKey, KeychainKeyValue}; use crate::keychain::{KeychainKey, KeychainKeyValue};
use crate::{cmdutil, ecdsautil, hmacutil}; use crate::{cmdutil, ecdsautil, hmacutil, util};
use clap::{App, Arg, ArgMatches, SubCommand}; use clap::{App, Arg, ArgMatches, SubCommand};
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use std::collections::BTreeMap; use std::collections::BTreeMap;
@@ -39,7 +39,7 @@ impl Command for CommandImpl {
if let Some(keychain_name) = keychain_name { if let Some(keychain_name) = keychain_name {
let keychain_key = KeychainKey::from_key_name_default(keychain_name); let keychain_key = KeychainKey::from_key_name_default(keychain_name);
if let Some(_) = keychain_key.get_password()? { if keychain_key.get_password()?.is_some() {
return simple_error!("Keychain key URI: {} exists", keychain_key.to_key_uri()); return simple_error!("Keychain key URI: {} exists", keychain_key.to_key_uri());
} }
} }
@@ -91,7 +91,7 @@ impl Command for CommandImpl {
json.insert("public_key_pem", public_key_pem); json.insert("public_key_pem", public_key_pem);
json.insert("public_key_jwk", jwk_ec_key.to_string()); json.insert("public_key_jwk", jwk_ec_key.to_string());
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} else { } else {
match keychain_key_uri { match keychain_key_uri {
None => { None => {

View File

@@ -1,4 +1,4 @@
use crate::cmdutil; use crate::{cmdutil, util};
use crate::keychain::{KeychainKey, KeychainKeyValue}; use crate::keychain::{KeychainKey, KeychainKeyValue};
use clap::{App, ArgMatches, SubCommand}; use clap::{App, ArgMatches, SubCommand};
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
@@ -27,10 +27,7 @@ impl Command for CommandImpl {
serde_json::from_slice(&keychain_key_value_bytes)?; serde_json::from_slice(&keychain_key_value_bytes)?;
util_msg::set_logger_std_out(false); util_msg::set_logger_std_out(false);
information!("Keychain key URI: {}", keychain_key.to_key_uri()); information!("Keychain key URI: {}", keychain_key.to_key_uri());
println!( util::print_pretty_json(&keychain_key_value);
"{}",
serde_json::to_string_pretty(&keychain_key_value).unwrap()
);
} else { } else {
return simple_error!("Keychain key URI: {} not found", keychain_key.to_key_uri()); return simple_error!("Keychain key URI: {} not found", keychain_key.to_key_uri());
} }

View File

@@ -1,7 +1,7 @@
use crate::cmdutil;
use crate::keychain::KeychainKey; use crate::keychain::KeychainKey;
use clap::{App, Arg, ArgMatches, SubCommand}; use clap::{App, Arg, ArgMatches, SubCommand};
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use crate::cmdutil;
pub struct CommandImpl; pub struct CommandImpl;
@@ -28,7 +28,7 @@ impl Command for CommandImpl {
if let Some(keychain_name) = keychain_name { if let Some(keychain_name) = keychain_name {
let keychain_key = KeychainKey::from_key_name_default(keychain_name); let keychain_key = KeychainKey::from_key_name_default(keychain_name);
if let Some(_) = keychain_key.get_password()? { if keychain_key.get_password()?.is_some() {
return simple_error!("Keychain key URI: {} exists", keychain_key.to_key_uri()); return simple_error!("Keychain key URI: {} exists", keychain_key.to_key_uri());
} }

View File

@@ -3,7 +3,7 @@ use std::collections::BTreeMap;
use clap::{App, ArgMatches, SubCommand}; use clap::{App, ArgMatches, SubCommand};
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use yubikey::YubiKey; use yubikey::YubiKey;
use crate::cmdutil; use crate::{cmdutil, util};
pub struct CommandImpl; pub struct CommandImpl;
@@ -38,7 +38,7 @@ impl Command for CommandImpl {
json.insert("keys", piv_keys.iter().map(|k| format!("{}", k.slot())).collect::<Vec<_>>().join(", ")); json.insert("keys", piv_keys.iter().map(|k| format!("{}", k.slot())).collect::<Vec<_>>().join(", "));
} }
println!("{}", serde_json::to_string_pretty(&json).expect("Convert to JSON failed!")); util::print_pretty_json(&json);
} else { } else {
success!("Name: {}", yk.name()); success!("Name: {}", yk.name());
success!("Version: {}", yk.version()); success!("Version: {}", yk.version());

View File

@@ -3,7 +3,7 @@ use std::collections::BTreeMap;
use clap::{App, Arg, ArgMatches, SubCommand}; use clap::{App, Arg, ArgMatches, SubCommand};
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use crate::cmdutil; use crate::{cmdutil, util};
use crate::ecdsautil::parse_ecdsa_r_and_s; use crate::ecdsautil::parse_ecdsa_r_and_s;
use crate::util::try_decode; use crate::util::try_decode;
@@ -51,7 +51,7 @@ impl Command for CommandImpl {
} }
if json_output { if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} }
Ok(None) Ok(None)
} }

View File

@@ -6,7 +6,7 @@ use openpgp_card::{KeyType, OpenPgp};
use openpgp_card_pcsc::PcscBackend; use openpgp_card_pcsc::PcscBackend;
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use std::collections::BTreeMap; use std::collections::BTreeMap;
use crate::cmdutil; use crate::{cmdutil, util};
const AGE_PUBLIC_KEY_PREFIX: &str = "age"; const AGE_PUBLIC_KEY_PREFIX: &str = "age";
@@ -66,7 +66,7 @@ impl Command for CommandImpl {
} }
if json_output { if json_output {
println!("{}", serde_json::to_string_pretty(&cards_output).unwrap()); util::print_pretty_json(&cards_output);
} }
Ok(None) Ok(None)
} }

View File

@@ -5,7 +5,7 @@ use openpgp_card::crypto_data::Cryptogram;
use rust_util::XResult; use rust_util::XResult;
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use crate::{cmdutil, pgpcardutil, pinutil}; use crate::{cmdutil, pgpcardutil, pinutil, util};
use crate::util::{base64_encode, read_stdin, try_decode}; use crate::util::{base64_encode, read_stdin, try_decode};
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
@@ -88,7 +88,7 @@ impl Command for CommandImpl {
json.insert("text_utf8", text); json.insert("text_utf8", text);
} }
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} }
Ok(None) Ok(None)
} }

View File

@@ -4,7 +4,7 @@ use clap::{App, Arg, ArgMatches, SubCommand};
use openpgp_card::{KeyType, OpenPgp}; use openpgp_card::{KeyType, OpenPgp};
use openpgp_card_pcsc::PcscBackend; use openpgp_card_pcsc::PcscBackend;
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use crate::cmdutil; use crate::{cmdutil, util};
use crate::pkiutil::openpgp_card_public_key_pem as public_key_pem; use crate::pkiutil::openpgp_card_public_key_pem as public_key_pem;
pub struct CommandImpl; pub struct CommandImpl;
@@ -135,7 +135,7 @@ impl Command for CommandImpl {
} }
if json_output { if json_output {
println!("{}", serde_json::to_string_pretty(&jsons).unwrap()); util::print_pretty_json(&jsons);
} }
Ok(None) Ok(None)
} }

View File

@@ -9,7 +9,7 @@ use rust_util::XResult;
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use sha2::{Sha256, Sha384, Sha512}; use sha2::{Sha256, Sha384, Sha512};
use crate::{cmdutil, pgpcardutil, pinutil}; use crate::{cmdutil, pgpcardutil, pinutil, util};
use crate::util::base64_encode; use crate::util::base64_encode;
const BUFF_SIZE: usize = 512 * 1024; const BUFF_SIZE: usize = 512 * 1024;
@@ -171,7 +171,7 @@ impl Command for CommandImpl {
} }
if json_output { if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} }
Ok(None) Ok(None)

View File

@@ -5,7 +5,7 @@ use rust_util::util_clap::{Command, CommandError};
use yubikey::piv::AlgorithmId; use yubikey::piv::AlgorithmId;
use yubikey::YubiKey; use yubikey::YubiKey;
use crate::{cmdutil, pinutil, pivutil}; use crate::{cmdutil, pinutil, pivutil, util};
use crate::util::{read_stdin, try_decode}; use crate::util::{read_stdin, try_decode};
pub struct CommandImpl; pub struct CommandImpl;
@@ -73,7 +73,8 @@ impl Command for CommandImpl {
json.insert("decrypted_data_hex", hex::encode(decrypted_data_bytes)); json.insert("decrypted_data_hex", hex::encode(decrypted_data_bytes));
json.insert("clear_data_hex", hex::encode(clear_data)); json.insert("clear_data_hex", hex::encode(clear_data));
json.insert("clear_data", String::from_utf8_lossy(clear_data).to_string()); json.insert("clear_data", String::from_utf8_lossy(clear_data).to_string());
println!("{}", serde_json::to_string_pretty(&json).unwrap());
util::print_pretty_json(&json);
} }
Ok(None) Ok(None)
} }

View File

@@ -7,7 +7,7 @@ use rust_util::util_clap::{Command, CommandError};
use yubikey::{PinPolicy, YubiKey}; use yubikey::{PinPolicy, YubiKey};
use yubikey::piv::{AlgorithmId, decrypt_data, metadata}; use yubikey::piv::{AlgorithmId, decrypt_data, metadata};
use crate::{cmdutil, ecdhutil, pinutil, pivutil}; use crate::{cmdutil, ecdhutil, pinutil, pivutil, util};
use crate::pivutil::get_algorithm_id; use crate::pivutil::get_algorithm_id;
pub struct CommandImpl; pub struct CommandImpl;
@@ -126,7 +126,7 @@ impl Command for CommandImpl {
} }
if json_output { if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} }
Ok(None) Ok(None)
} }

View File

@@ -7,7 +7,7 @@ use yubikey::piv::{metadata, sign_data, AlgorithmId, ManagementAlgorithmId};
use yubikey::YubiKey; use yubikey::YubiKey;
use crate::util::base64_encode; use crate::util::base64_encode;
use crate::{argsutil, cmdutil, pivutil}; use crate::{argsutil, cmdutil, pivutil, util};
pub struct CommandImpl; pub struct CommandImpl;
@@ -80,7 +80,7 @@ impl Command for CommandImpl {
} }
if json_output { if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} }
Ok(None) Ok(None)
} }

View File

@@ -36,7 +36,6 @@ impl Command for CommandImpl {
success!("Generate key success: {:?}", public_key_info); success!("Generate key success: {:?}", public_key_info);
Ok(None) Ok(None)
} }
} }

View File

@@ -9,7 +9,7 @@ use x509_parser::parse_x509_certificate;
use yubikey::{Key, YubiKey}; use yubikey::{Key, YubiKey};
use yubikey::piv::{AlgorithmId, metadata}; use yubikey::piv::{AlgorithmId, metadata};
use crate::{cmdutil, pivutil}; use crate::{cmdutil, pivutil, util};
use crate::pivutil::{get_algorithm_id_by_certificate, slot_equals, ToStr}; use crate::pivutil::{get_algorithm_id_by_certificate, slot_equals, ToStr};
use crate::pkiutil::bytes_to_pem; use crate::pkiutil::bytes_to_pem;
use crate::sshutil::SshVecWriter; use crate::sshutil::SshVecWriter;
@@ -134,7 +134,7 @@ impl Command for CommandImpl {
} }
if json_output { if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} }
Ok(None) Ok(None)
} }

View File

@@ -5,7 +5,7 @@ use rust_util::util_clap::{Command, CommandError};
use yubikey::{piv, YubiKey}; use yubikey::{piv, YubiKey};
use yubikey::piv::{AlgorithmId, SlotId}; use yubikey::piv::{AlgorithmId, SlotId};
use crate::{cmdutil, pinutil, pivutil, rsautil}; use crate::{cmdutil, pinutil, pivutil, rsautil, util};
use crate::util::base64_encode; use crate::util::base64_encode;
pub struct CommandImpl; pub struct CommandImpl;
@@ -53,7 +53,8 @@ impl Command for CommandImpl {
json.insert("hash_hex", hex::encode(&sha256)); json.insert("hash_hex", hex::encode(&sha256));
json.insert("sign_hex", hex::encode(sign_bytes)); json.insert("sign_hex", hex::encode(sign_bytes));
json.insert("sign_base64", base64_encode(sign_bytes)); json.insert("sign_base64", base64_encode(sign_bytes));
println!("{}", serde_json::to_string_pretty(&json).unwrap());
util::print_pretty_json(&json);
} else { } else {
success!("Signature HEX: {}", hex::encode(sign_bytes)); success!("Signature HEX: {}", hex::encode(sign_bytes));
success!("Signature base64: {}", base64_encode(sign_bytes)); success!("Signature base64: {}", base64_encode(sign_bytes));

View File

@@ -9,7 +9,7 @@ use tabled::{Table, Tabled};
use x509_parser::parse_x509_certificate; use x509_parser::parse_x509_certificate;
use yubikey::piv::{metadata, SlotId}; use yubikey::piv::{metadata, SlotId};
use yubikey::{Certificate, YubiKey}; use yubikey::{Certificate, YubiKey};
use crate::cmdutil; use crate::{cmdutil, util};
use crate::pivutil::{get_algorithm_id_by_certificate, ToStr, ORDERED_SLOTS}; use crate::pivutil::{get_algorithm_id_by_certificate, ToStr, ORDERED_SLOTS};
const NA: &str = "N/A"; const NA: &str = "N/A";
@@ -99,7 +99,7 @@ impl Command for CommandImpl {
output.insert("piv_slots".to_string(), Value::Array(piv_slots_values)); output.insert("piv_slots".to_string(), Value::Array(piv_slots_values));
} }
if json_output { if json_output {
println!("{}", serde_json::to_string_pretty(&output).unwrap()); util::print_pretty_json(&output);
} }
Ok(None) Ok(None)

View File

@@ -7,7 +7,7 @@ use rust_util::util_clap::{Command, CommandError};
use yubikey::{Key, YubiKey}; use yubikey::{Key, YubiKey};
use yubikey::piv::{AlgorithmId, SlotId}; use yubikey::piv::{AlgorithmId, SlotId};
use crate::{argsutil, cmdutil, ecdsautil, pivutil}; use crate::{argsutil, cmdutil, ecdsautil, pivutil, util};
use crate::ecdsautil::EcdsaAlgorithm; use crate::ecdsautil::EcdsaAlgorithm;
use crate::pivutil::slot_equals; use crate::pivutil::slot_equals;
@@ -99,7 +99,7 @@ impl Command for CommandImpl {
} }
if json_output { if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} }
Ok(None) Ok(None)
} }

View File

@@ -8,7 +8,7 @@ use openssl::rsa::Rsa;
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use rust_util::util_msg; use rust_util::util_msg;
use rust_util::util_msg::MessageType; use rust_util::util_msg::MessageType;
use crate::cmdutil; use crate::{cmdutil, util};
use crate::util::{read_stdin, try_decode}; use crate::util::{read_stdin, try_decode};
pub struct CommandImpl; pub struct CommandImpl;
@@ -86,7 +86,7 @@ impl Command for CommandImpl {
} }
if json_output { if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} }
Ok(None) Ok(None)

View File

@@ -6,7 +6,7 @@ use openssl::encrypt::Encrypter;
use openssl::pkey::PKey; use openssl::pkey::PKey;
use openssl::rsa::Rsa; use openssl::rsa::Rsa;
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use crate::cmdutil; use crate::{cmdutil, util};
use crate::digest::sha256_bytes; use crate::digest::sha256_bytes;
pub struct CommandImpl; pub struct CommandImpl;
@@ -71,7 +71,7 @@ impl Command for CommandImpl {
} }
if json_output { if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} }
Ok(None) Ok(None)

View File

@@ -1,7 +1,7 @@
use std::collections::BTreeMap; use crate::{cmdutil, seutil, util};
use crate::{cmdutil, seutil};
use clap::{App, ArgMatches, SubCommand}; use clap::{App, ArgMatches, SubCommand};
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use std::collections::BTreeMap;
pub struct CommandImpl; pub struct CommandImpl;
@@ -11,8 +11,9 @@ impl Command for CommandImpl {
} }
fn subcommand<'a>(&self) -> App<'a, 'a> { fn subcommand<'a>(&self) -> App<'a, 'a> {
SubCommand::with_name(self.name()).about("Secure Enclave subcommand") SubCommand::with_name(self.name())
.arg(cmdutil::build_json_arg()) .about("Secure Enclave subcommand")
.arg(cmdutil::build_json_arg())
} }
fn run(&self, _arg_matches: &ArgMatches, sub_arg_matches: &ArgMatches) -> CommandError { fn run(&self, _arg_matches: &ArgMatches, sub_arg_matches: &ArgMatches) -> CommandError {
@@ -22,15 +23,14 @@ impl Command for CommandImpl {
if json_output { if json_output {
json.insert("se_supported", seutil::is_support_se()); json.insert("se_supported", seutil::is_support_se());
} else {
if seutil::is_support_se() {
success!("Secure Enclave is supported.")
} else {
failure!("Secure Enclave is NOT supported.")
}
}
if json_output {} util::print_pretty_json(&json);
} else {
success!(
"Secure Enclave is {}supported.",
iff!(seutil::is_support_se(), "", "NOT ")
);
}
Ok(None) Ok(None)
} }
} }

View File

@@ -1,5 +1,5 @@
use crate::keyutil::{parse_key_uri, KeyUri}; use crate::keyutil::{parse_key_uri, KeyUri};
use crate::{cmdutil, seutil}; use crate::{cmdutil, seutil, util};
use clap::{App, Arg, ArgMatches, SubCommand}; use clap::{App, Arg, ArgMatches, SubCommand};
use p256::elliptic_curve::sec1::FromEncodedPoint; use p256::elliptic_curve::sec1::FromEncodedPoint;
use p256::{EncodedPoint, PublicKey}; use p256::{EncodedPoint, PublicKey};
@@ -75,7 +75,7 @@ impl Command for CommandImpl {
let mut json = BTreeMap::<&'_ str, String>::new(); let mut json = BTreeMap::<&'_ str, String>::new();
json.insert("shared_secret_hex", dh_hex); json.insert("shared_secret_hex", dh_hex);
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} else { } else {
information!("Shared secret: {}", dh_hex); information!("Shared secret: {}", dh_hex);
} }

View File

@@ -1,5 +1,5 @@
use crate::keyutil::{parse_key_uri, KeyUri}; use crate::keyutil::{parse_key_uri, KeyUri};
use crate::{cmdutil, seutil}; use crate::{cmdutil, seutil, util};
use crate::util::{base64_decode, base64_encode}; use crate::util::{base64_decode, base64_encode};
use clap::{App, Arg, ArgMatches, SubCommand}; use clap::{App, Arg, ArgMatches, SubCommand};
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
@@ -63,7 +63,7 @@ impl Command for CommandImpl {
json.insert("signature_base64", base64_encode(&signature)); json.insert("signature_base64", base64_encode(&signature));
json.insert("signature_hex", hex::encode(&signature)); json.insert("signature_hex", hex::encode(&signature));
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} else { } else {
success!("Signature: {}", base64_encode(&signature)); success!("Signature: {}", base64_encode(&signature));
} }

View File

@@ -1,5 +1,5 @@
use crate::pkiutil::bytes_to_pem; use crate::pkiutil::bytes_to_pem;
use crate::{cmdutil, seutil}; use crate::{cmdutil, seutil, util};
use crate::util::base64_encode; use crate::util::base64_encode;
use clap::{App, Arg, ArgMatches, SubCommand}; use clap::{App, Arg, ArgMatches, SubCommand};
use p256::PublicKey; use p256::PublicKey;
@@ -75,20 +75,21 @@ pub fn print_se_key(
public_key_der: &[u8], public_key_der: &[u8],
key_uri: &str, key_uri: &str,
) { ) {
let public_key_point_hex = hex::encode(&public_key_point); let public_key_point_hex = hex::encode(public_key_point);
let public_key_pem = bytes_to_pem("PUBLIC KEY", &*public_key_der); let public_key_pem = bytes_to_pem("PUBLIC KEY", public_key_der);
let public_key = PublicKey::from_public_key_pem(&public_key_pem).ok(); let public_key = PublicKey::from_public_key_pem(&public_key_pem).ok();
let public_key_jwk = public_key.map(|key| key.to_jwk_string()); let public_key_jwk = public_key.map(|key| key.to_jwk_string());
if json_output { if json_output {
let mut json = BTreeMap::<&'_ str, String>::new(); let mut json = BTreeMap::<&'_ str, String>::new();
json.insert("public_key_point", public_key_point_hex); json.insert("public_key_point", public_key_point_hex);
json.insert("public_key_pem", base64_encode(&*public_key_der)); json.insert("public_key_pem", base64_encode(public_key_der));
if let Some(public_key_jwk) = public_key_jwk { if let Some(public_key_jwk) = public_key_jwk {
json.insert("public_key_jwk", base64_encode(public_key_jwk)); json.insert("public_key_jwk", base64_encode(public_key_jwk));
} }
json.insert("key", key_uri.to_string()); json.insert("key", key_uri.to_string());
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} else { } else {
success!("Public key(point): {}", public_key_point_hex); success!("Public key(point): {}", public_key_point_hex);
success!("Public key PEM: \n{}", public_key_pem); success!("Public key PEM: \n{}", public_key_pem);

View File

@@ -41,7 +41,7 @@ impl Command for CommandImpl {
se_key_uri.usage == KeyUsage::Singing, se_key_uri.usage == KeyUsage::Singing,
)?; )?;
print_se_key(json_output, &public_key_point, &public_key_der, &key_uri); print_se_key(json_output, &public_key_point, &public_key_der, key_uri);
Ok(None) Ok(None)
} }

View File

@@ -34,8 +34,6 @@ impl Command for CommandImpl {
fn run(&self, _arg_matches: &ArgMatches, sub_arg_matches: &ArgMatches) -> CommandError { fn run(&self, _arg_matches: &ArgMatches, sub_arg_matches: &ArgMatches) -> CommandError {
let json_output = cmdutil::check_json_output(sub_arg_matches); let json_output = cmdutil::check_json_output(sub_arg_matches);
let mut json = BTreeMap::<&'_ str, String>::new();
let slot = opt_value_result!( let slot = opt_value_result!(
sub_arg_matches.value_of("slot"), sub_arg_matches.value_of("slot"),
"--slot must assigned, e.g. 82, 83 ... 95, 9a, 9c, 9d, 9e" "--slot must assigned, e.g. 82, 83 ... 95, 9a, 9c, 9d, 9e"
@@ -48,21 +46,25 @@ impl Command for CommandImpl {
let pin_opt = pivutil::check_read_pin(&mut yk, slot_id, sub_arg_matches); let pin_opt = pivutil::check_read_pin(&mut yk, slot_id, sub_arg_matches);
let token_string = sign_jwt(&mut yk, slot_id, &pin_opt, header, &payload, &jwt_claims)?; let token_string = sign_jwt(&mut yk, slot_id, &pin_opt, header, &payload, &jwt_claims)?;
print_jwt_token(json_output, token_string);
debugging!("Singed JWT: {}", token_string);
if json_output {
json.insert("token", token_string.clone());
} else {
success!("Singed JWT: {}", token_string);
}
if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap());
}
Ok(None) Ok(None)
} }
} }
pub fn print_jwt_token(json_output: bool, token_string: String) {
if json_output {
debugging!("Singed JWT: {}", token_string);
let mut json = BTreeMap::<&'_ str, String>::new();
json.insert("token", token_string.clone());
util::print_pretty_json(&json);
} else {
success!("Singed JWT: {}", token_string);
}
}
pub fn fill_sign_jwt_app_args<'a>(app: App<'a, 'a>) -> App<'a, 'a> { pub fn fill_sign_jwt_app_args<'a>(app: App<'a, 'a>) -> App<'a, 'a> {
app.arg(Arg::with_name("key-id").short("K").long("key-id").takes_value(true).help("Header key ID")) app.arg(Arg::with_name("key-id").short("K").long("key-id").takes_value(true).help("Header key ID"))
.arg(Arg::with_name("claims").short("C").long("claims").takes_value(true).multiple(true).help("Claims, key:value")) .arg(Arg::with_name("claims").short("C").long("claims").takes_value(true).multiple(true).help("Claims, key:value"))

View File

@@ -6,9 +6,8 @@ use jwt::{AlgorithmType, Header, ToBase64};
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use rust_util::XResult; use rust_util::XResult;
use serde_json::{Map, Value}; use serde_json::{Map, Value};
use std::collections::BTreeMap;
use crate::cmd_sign_jwt::{build_jwt_parts, merge_header_claims, merge_payload_claims}; use crate::cmd_sign_jwt::{build_jwt_parts, merge_header_claims, merge_payload_claims, print_jwt_token};
use crate::ecdsautil::parse_ecdsa_to_rs; use crate::ecdsautil::parse_ecdsa_to_rs;
use crate::keyutil::{parse_key_uri, KeyUri}; use crate::keyutil::{parse_key_uri, KeyUri};
use crate::{cmd_sign_jwt, cmdutil, hmacutil, util}; use crate::{cmd_sign_jwt, cmdutil, hmacutil, util};
@@ -32,8 +31,6 @@ impl Command for CommandImpl {
fn run(&self, _arg_matches: &ArgMatches, sub_arg_matches: &ArgMatches) -> CommandError { fn run(&self, _arg_matches: &ArgMatches, sub_arg_matches: &ArgMatches) -> CommandError {
let json_output = cmdutil::check_json_output(sub_arg_matches); let json_output = cmdutil::check_json_output(sub_arg_matches);
let mut json = BTreeMap::<&'_ str, String>::new();
let private_key = opt_value_result!( let private_key = opt_value_result!(
sub_arg_matches.value_of("key"), sub_arg_matches.value_of("key"),
"Private key PKCS#8 DER base64 encoded or PEM" "Private key PKCS#8 DER base64 encoded or PEM"
@@ -45,17 +42,8 @@ impl Command for CommandImpl {
let (header, payload, jwt_claims) = build_jwt_parts(sub_arg_matches)?; let (header, payload, jwt_claims) = build_jwt_parts(sub_arg_matches)?;
let token_string = sign_jwt(&se_key_uri.private_key, header, &payload, &jwt_claims)?; let token_string = sign_jwt(&se_key_uri.private_key, header, &payload, &jwt_claims)?;
print_jwt_token(json_output, token_string);
debugging!("Singed JWT: {}", token_string);
if json_output {
json.insert("token", token_string.clone());
} else {
success!("Singed JWT: {}", token_string);
}
if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap());
}
Ok(None) Ok(None)
} }
} }

View File

@@ -1,12 +1,10 @@
use std::collections::BTreeMap;
use clap::{App, Arg, ArgMatches, SubCommand}; use clap::{App, Arg, ArgMatches, SubCommand};
use jwt::{AlgorithmType, Header, ToBase64}; use jwt::{AlgorithmType, Header, ToBase64};
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use rust_util::XResult; use rust_util::XResult;
use serde_json::{Map, Value}; use serde_json::{Map, Value};
use crate::cmd_sign_jwt::{build_jwt_parts, merge_header_claims, merge_payload_claims}; use crate::cmd_sign_jwt::{build_jwt_parts, merge_header_claims, merge_payload_claims, print_jwt_token};
use crate::keychain::{KeychainKey, KeychainKeyValue}; use crate::keychain::{KeychainKey, KeychainKeyValue};
use crate::{cmd_sign_jwt, cmdutil, digest, ecdsautil, hmacutil, keychain, rsautil, util}; use crate::{cmd_sign_jwt, cmdutil, digest, ecdsautil, hmacutil, keychain, rsautil, util};
@@ -29,8 +27,6 @@ impl Command for CommandImpl {
fn run(&self, _arg_matches: &ArgMatches, sub_arg_matches: &ArgMatches) -> CommandError { fn run(&self, _arg_matches: &ArgMatches, sub_arg_matches: &ArgMatches) -> CommandError {
let json_output = cmdutil::check_json_output(sub_arg_matches); let json_output = cmdutil::check_json_output(sub_arg_matches);
let mut json = BTreeMap::<&'_ str, String>::new();
let private_key = opt_value_result!( let private_key = opt_value_result!(
sub_arg_matches.value_of("private-key"), sub_arg_matches.value_of("private-key"),
"Private key PKCS#8 DER base64 encoded or PEM" "Private key PKCS#8 DER base64 encoded or PEM"
@@ -57,17 +53,8 @@ impl Command for CommandImpl {
let (header, payload, jwt_claims) = build_jwt_parts(sub_arg_matches)?; let (header, payload, jwt_claims) = build_jwt_parts(sub_arg_matches)?;
let token_string = sign_jwt(&private_key, header, &payload, &jwt_claims)?; let token_string = sign_jwt(&private_key, header, &payload, &jwt_claims)?;
print_jwt_token(json_output, token_string);
debugging!("Singed JWT: {}", token_string);
if json_output {
json.insert("token", token_string.clone());
} else {
success!("Singed JWT: {}", token_string);
}
if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap());
}
Ok(None) Ok(None)
} }
} }

View File

@@ -1,7 +1,7 @@
use crate::digest::sha256_bytes; use crate::digest::sha256_bytes;
use crate::pivutil::{get_algorithm_id_by_certificate, slot_equals, ToStr}; use crate::pivutil::{get_algorithm_id_by_certificate, slot_equals, ToStr};
use crate::sshutil::SshVecWriter; use crate::sshutil::SshVecWriter;
use crate::{cmdutil, pivutil}; use crate::{cmdutil, pivutil, util};
use base64::engine::general_purpose::STANDARD; use base64::engine::general_purpose::STANDARD;
use base64::Engine; use base64::Engine;
use clap::{App, Arg, ArgMatches, SubCommand}; use clap::{App, Arg, ArgMatches, SubCommand};
@@ -28,8 +28,6 @@ impl Command for CommandImpl {
fn run(&self, _arg_matches: &ArgMatches, sub_arg_matches: &ArgMatches) -> CommandError { fn run(&self, _arg_matches: &ArgMatches, sub_arg_matches: &ArgMatches) -> CommandError {
let json_output = cmdutil::check_json_output(sub_arg_matches); let json_output = cmdutil::check_json_output(sub_arg_matches);
let mut json = BTreeMap::<&'_ str, String>::new();
let slot = opt_value_result!( let slot = opt_value_result!(
sub_arg_matches.value_of("slot"), sub_arg_matches.value_of("slot"),
"--slot must assigned, e.g. 82, 83 ... 95, 9a, 9c, 9d, 9e" "--slot must assigned, e.g. 82, 83 ... 95, 9a, 9c, 9d, 9e"
@@ -120,14 +118,13 @@ impl Command for CommandImpl {
); );
if json_output { if json_output {
let mut json = BTreeMap::<&'_ str, String>::new();
json.insert("ssh_pub_key", ssh_pub_key); json.insert("ssh_pub_key", ssh_pub_key);
util::print_pretty_json(&json);
} else { } else {
println!("{}", &ssh_pub_key); println!("{}", &ssh_pub_key);
} }
if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap());
}
Ok(None) Ok(None)
} }
} }

View File

@@ -12,7 +12,7 @@ use rust_util::util_clap::{Command, CommandError};
use x509_parser::certificate::X509Certificate; use x509_parser::certificate::X509Certificate;
use x509_parser::prelude::FromDer; use x509_parser::prelude::FromDer;
use crate::{cmdutil, digest}; use crate::{cmdutil, digest, util};
use crate::fido; use crate::fido;
use crate::fido::{U2fRegistrationData, U2fV2Challenge}; use crate::fido::{U2fRegistrationData, U2fV2Challenge};
use crate::util::base64_encode; use crate::util::base64_encode;
@@ -148,7 +148,7 @@ impl Command for CommandImpl {
} }
} }
if json_output { if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} }
Ok(None) Ok(None)
} }

View File

@@ -13,7 +13,7 @@ use openssl::pkey::PKey;
use openssl::sign::Verifier; use openssl::sign::Verifier;
use rust_util::util_clap::{Command, CommandError}; use rust_util::util_clap::{Command, CommandError};
use crate::{cmdutil, digest}; use crate::{cmdutil, digest, util};
use crate::fido; use crate::fido;
use crate::fido::U2fV2Challenge; use crate::fido::U2fV2Challenge;
use crate::util::base64_encode; use crate::util::base64_encode;
@@ -162,7 +162,7 @@ impl Command for CommandImpl {
} }
} }
if json_output { if json_output {
println!("{}", serde_json::to_string_pretty(&json).unwrap()); util::print_pretty_json(&json);
} }
Ok(None) Ok(None)
} }

View File

@@ -31,22 +31,14 @@ pub fn parse_ecdsa_r_and_s(signature_der: &[u8]) -> XResult<(Vec<u8>, Vec<u8>)>
match &seq[0].content { match &seq[0].content {
BerObjectContent::Integer(r) => { BerObjectContent::Integer(r) => {
debugging!("Signature r: {}", hex::encode(r)); debugging!("Signature r: {}", hex::encode(r));
if r.len() == ((256 / 8) + 1) || r.len() == ((384 / 8) + 1) { vec_r = trim_point_leading_zero(r);
vec_r = r[1..].to_vec();
} else {
vec_r = r.to_vec();
}
} }
_ => return simple_error!("Parse signature failed: [0]not integer"), _ => return simple_error!("Parse signature failed: [0]not integer"),
} }
match &seq[1].content { match &seq[1].content {
BerObjectContent::Integer(s) => { BerObjectContent::Integer(s) => {
debugging!("Signature s: {}", hex::encode(s)); debugging!("Signature s: {}", hex::encode(s));
if s.len() == ((256 / 8) + 1) || s.len() == ((384 / 8) + 1) { vec_s = trim_point_leading_zero(s);
vec_s = s[1..].to_vec();
} else {
vec_s = s.to_vec();
}
} }
_ => return simple_error!("Parse signature failed: [1]not integer"), _ => return simple_error!("Parse signature failed: [1]not integer"),
} }
@@ -56,6 +48,14 @@ pub fn parse_ecdsa_r_and_s(signature_der: &[u8]) -> XResult<(Vec<u8>, Vec<u8>)>
Ok((vec_r, vec_s)) Ok((vec_r, vec_s))
} }
fn trim_point_leading_zero(p: &[u8]) -> Vec<u8> {
if p.len() == ((256 / 8) + 1) || p.len() == ((384 / 8) + 1) {
p[1..].to_vec()
} else {
p.to_vec()
}
}
pub fn generate_p256_keypair() -> XResult<(String, String, String, JwkEcKey)> { pub fn generate_p256_keypair() -> XResult<(String, String, String, JwkEcKey)> {
let secret_key = p256::SecretKey::random(&mut rand::thread_rng()); let secret_key = p256::SecretKey::random(&mut rand::thread_rng());
let secret_key_der_base64 = base64_encode(secret_key.to_pkcs8_der()?.as_bytes()); let secret_key_der_base64 = base64_encode(secret_key.to_pkcs8_der()?.as_bytes());

View File

@@ -9,6 +9,7 @@ use yubico_manager::hmacmode::HmacKey;
use yubico_manager::sec::hmac_sha1; use yubico_manager::sec::hmac_sha1;
use yubico_manager::Yubico; use yubico_manager::Yubico;
use crate::digest::{copy_sha256, sha256_bytes}; use crate::digest::{copy_sha256, sha256_bytes};
use crate::util;
use crate::util::{base64_decode, base64_encode}; use crate::util::{base64_decode, base64_encode};
const HMAC_ENC_PREFIX: &str = "hmac_enc:"; const HMAC_ENC_PREFIX: &str = "hmac_enc:";
@@ -142,7 +143,7 @@ pub fn output_hmac_result(sub_arg_matches: &ArgMatches, json_output: bool, chall
hex_sha384.map(|hex_sha384| json.insert("response_sha384_hex", hex::encode(hex_sha384))); hex_sha384.map(|hex_sha384| json.insert("response_sha384_hex", hex::encode(hex_sha384)));
hex_sha512.map(|hex_sha512| json.insert("response_sha512_hex", hex::encode(hex_sha512))); hex_sha512.map(|hex_sha512| json.insert("response_sha512_hex", hex::encode(hex_sha512)));
println!("{}", serde_json::to_string_pretty(&json).expect("Convert to JSON failed!")); util::print_pretty_json(&json);
} else { } else {
success!("Challenge HEX: {}", hex::encode(challenge_bytes)); success!("Challenge HEX: {}", hex::encode(challenge_bytes));
success!("Response HEX: {}", hex_string); success!("Response HEX: {}", hex_string);

View File

@@ -4,6 +4,7 @@ use std::io::Read;
use base64::{DecodeError, Engine}; use base64::{DecodeError, Engine};
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
use rust_util::XResult; use rust_util::XResult;
use serde::Serialize;
pub fn base64_encode<T: AsRef<[u8]>>(input: T) -> String { pub fn base64_encode<T: AsRef<[u8]>>(input: T) -> String {
STANDARD.encode(input) STANDARD.encode(input)
@@ -48,3 +49,10 @@ pub fn read_file_or_stdin(file: &str) -> XResult<Vec<u8>> {
Ok(opt_result!(fs::read(file), "Read file: {} failed: {}", file)) Ok(opt_result!(fs::read(file), "Read file: {} failed: {}", file))
} }
} }
pub fn print_pretty_json<T>(value: &T)
where
T: ?Sized + Serialize,
{
println!("{}", serde_json::to_string_pretty(value).unwrap());
}