move things to use default handler mechanism

This commit is contained in:
Ryan Heywood 2025-01-04 01:04:52 -05:00
parent f8db8702ce
commit c46f9e48b7
Signed by: ryan
GPG Key ID: 8E401478A3FBEF72
11 changed files with 76 additions and 84 deletions

View File

@ -11,7 +11,7 @@ pub struct BincodeLayer<'a, Request> {
phantom_request: PhantomData<&'a Request>, phantom_request: PhantomData<&'a Request>,
} }
impl<'a, Request> BincodeLayer<'a, Request> { impl<Request> BincodeLayer<'_, Request> {
/// Create a new [`BincodeLayer`]. /// Create a new [`BincodeLayer`].
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
@ -21,7 +21,7 @@ impl<'a, Request> BincodeLayer<'a, Request> {
} }
} }
impl<'a, Request> Default for BincodeLayer<'a, Request> { impl<Request> Default for BincodeLayer<'_, Request> {
fn default() -> Self { fn default() -> Self {
Self::new() Self::new()
} }

View File

@ -7,7 +7,7 @@ use std::{
process::ExitCode, process::ExitCode,
}; };
use keyfork_prompt::{DefaultTerminal, default_terminal}; use keyfork_prompt::default_handler;
use keyfork_shard::{openpgp::OpenPGP, Format}; use keyfork_shard::{openpgp::OpenPGP, Format};
type Result<T, E = Box<dyn std::error::Error>> = std::result::Result<T, E>; type Result<T, E = Box<dyn std::error::Error>> = std::result::Result<T, E>;
@ -32,8 +32,8 @@ fn run() -> Result<()> {
_ => panic!("Usage: {program_name} <shard> [key_discovery]"), _ => panic!("Usage: {program_name} <shard> [key_discovery]"),
}; };
let openpgp = OpenPGP::<DefaultTerminal>::new(); let openpgp = OpenPGP;
let prompt_handler = default_terminal()?; let prompt_handler = default_handler()?;
let bytes = openpgp.decrypt_all_shards_to_secret(key_discovery.as_deref(), messages_file, prompt_handler)?; let bytes = openpgp.decrypt_all_shards_to_secret(key_discovery.as_deref(), messages_file, prompt_handler)?;
print!("{}", smex::encode(bytes)); print!("{}", smex::encode(bytes));

View File

@ -7,7 +7,7 @@ use std::{
process::ExitCode, process::ExitCode,
}; };
use keyfork_prompt::{DefaultTerminal, default_terminal}; use keyfork_prompt::default_handler;
use keyfork_shard::{Format, openpgp::OpenPGP}; use keyfork_shard::{Format, openpgp::OpenPGP};
type Result<T, E = Box<dyn std::error::Error>> = std::result::Result<T, E>; type Result<T, E = Box<dyn std::error::Error>> = std::result::Result<T, E>;
@ -32,8 +32,8 @@ fn run() -> Result<()> {
_ => panic!("Usage: {program_name} <shard> [key_discovery]"), _ => panic!("Usage: {program_name} <shard> [key_discovery]"),
}; };
let openpgp = OpenPGP::<DefaultTerminal>::new(); let openpgp = OpenPGP;
let prompt_handler = default_terminal()?; let prompt_handler = default_handler()?;
openpgp.decrypt_one_shard_for_transport(key_discovery.as_deref(), messages_file, prompt_handler)?; openpgp.decrypt_one_shard_for_transport(key_discovery.as_deref(), messages_file, prompt_handler)?;

View File

@ -2,7 +2,6 @@
use std::{env, path::PathBuf, process::ExitCode, str::FromStr}; use std::{env, path::PathBuf, process::ExitCode, str::FromStr};
use keyfork_prompt::terminal::DefaultTerminal;
use keyfork_shard::{Format, openpgp::OpenPGP}; use keyfork_shard::{Format, openpgp::OpenPGP};
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@ -51,7 +50,7 @@ fn run() -> Result<()> {
smex::decode(line?)? smex::decode(line?)?
}; };
let openpgp = OpenPGP::<DefaultTerminal>::new(); let openpgp = OpenPGP;
openpgp.shard_and_encrypt(threshold, max, &input, key_discovery.as_path(), std::io::stdout())?; openpgp.shard_and_encrypt(threshold, max, &input, key_discovery.as_path(), std::io::stdout())?;
Ok(()) Ok(())

View File

@ -3,7 +3,8 @@
use std::{ use std::{
io::{stdin, stdout, Read, Write}, io::{stdin, stdout, Read, Write},
sync::{Arc, Mutex}, sync::Mutex,
rc::Rc,
}; };
use aes_gcm::{ use aes_gcm::{
@ -136,7 +137,7 @@ pub trait Format {
&self, &self,
private_keys: Option<Self::PrivateKeyData>, private_keys: Option<Self::PrivateKeyData>,
encrypted_messages: &[Self::EncryptedData], encrypted_messages: &[Self::EncryptedData],
prompt: Arc<Mutex<impl PromptHandler>>, prompt: Rc<Mutex<Box<dyn PromptHandler>>>,
) -> Result<(Vec<Share>, u8), Self::Error>; ) -> Result<(Vec<Share>, u8), Self::Error>;
/// Decrypt a single share and associated metadata from a reaable input. For the current /// Decrypt a single share and associated metadata from a reaable input. For the current
@ -150,7 +151,7 @@ pub trait Format {
&self, &self,
private_keys: Option<Self::PrivateKeyData>, private_keys: Option<Self::PrivateKeyData>,
encrypted_data: &[Self::EncryptedData], encrypted_data: &[Self::EncryptedData],
prompt: Arc<Mutex<impl PromptHandler>>, prompt: Rc<Mutex<Box<dyn PromptHandler>>>,
) -> Result<(Share, u8), Self::Error>; ) -> Result<(Share, u8), Self::Error>;
/// Decrypt multiple shares and combine them to recreate a secret. /// Decrypt multiple shares and combine them to recreate a secret.
@ -162,7 +163,7 @@ pub trait Format {
&self, &self,
private_key_discovery: Option<impl KeyDiscovery<Self>>, private_key_discovery: Option<impl KeyDiscovery<Self>>,
reader: impl Read + Send + Sync, reader: impl Read + Send + Sync,
prompt: impl PromptHandler, prompt: Box<dyn PromptHandler>,
) -> Result<Vec<u8>, Box<dyn std::error::Error>> { ) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let private_keys = private_key_discovery let private_keys = private_key_discovery
.map(|p| p.discover_private_keys()) .map(|p| p.discover_private_keys())
@ -171,7 +172,7 @@ pub trait Format {
let (shares, threshold) = self.decrypt_all_shards( let (shares, threshold) = self.decrypt_all_shards(
private_keys, private_keys,
&encrypted_messages, &encrypted_messages,
Arc::new(Mutex::new(prompt)), Rc::new(Mutex::new(prompt)),
)?; )?;
let secret = Sharks(threshold) let secret = Sharks(threshold)
@ -192,9 +193,9 @@ pub trait Format {
&self, &self,
private_key_discovery: Option<impl KeyDiscovery<Self>>, private_key_discovery: Option<impl KeyDiscovery<Self>>,
reader: impl Read + Send + Sync, reader: impl Read + Send + Sync,
prompt: impl PromptHandler, prompt: Box<dyn PromptHandler>,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
let prompt = Arc::new(Mutex::new(prompt)); let prompt = Rc::new(Mutex::new(prompt));
// parse input // parse input
let private_keys = private_key_discovery let private_keys = private_key_discovery
@ -236,7 +237,7 @@ pub trait Format {
}; };
let mut prompt = prompt.lock().expect(bug!(POISONED_MUTEX)); let mut prompt = prompt.lock().expect(bug!(POISONED_MUTEX));
prompt_validated_wordlist::<English, _>( prompt_validated_wordlist::<English, _>(
&mut *prompt, &mut **prompt,
QRCODE_COULDNT_READ, QRCODE_COULDNT_READ,
3, 3,
&*validator.to_fn(), &*validator.to_fn(),

View File

@ -5,10 +5,10 @@
use std::{ use std::{
collections::HashMap, collections::HashMap,
io::{Read, Write}, io::{Read, Write},
marker::PhantomData,
path::Path, path::Path,
str::FromStr, str::FromStr,
sync::{Arc, Mutex}, sync::Mutex,
rc::Rc,
}; };
use keyfork_bug::bug; use keyfork_bug::bug;
@ -186,18 +186,9 @@ impl EncryptedMessage {
} }
/// Encoding and decoding shards using OpenPGP. /// Encoding and decoding shards using OpenPGP.
pub struct OpenPGP<P: PromptHandler> { pub struct OpenPGP;
p: PhantomData<P>,
}
impl<P: PromptHandler> OpenPGP<P> { impl OpenPGP {
#[allow(clippy::new_without_default, missing_docs)]
pub fn new() -> Self {
Self { p: PhantomData }
}
}
impl<P: PromptHandler> OpenPGP<P> {
/// Read all OpenPGP certificates in a path and return a [`Vec`] of them. /// Read all OpenPGP certificates in a path and return a [`Vec`] of them.
/// ///
/// Certificates are read from a file, or from files one level deep in a directory. /// Certificates are read from a file, or from files one level deep in a directory.
@ -256,7 +247,7 @@ impl<P: PromptHandler> OpenPGP<P> {
const METADATA_MESSAGE_MISSING: &str = "Metadata message was not found in parsed packets"; const METADATA_MESSAGE_MISSING: &str = "Metadata message was not found in parsed packets";
impl<P: PromptHandler> Format for OpenPGP<P> { impl Format for OpenPGP {
type Error = Error; type Error = Error;
type PublicKey = Cert; type PublicKey = Cert;
type PrivateKeyData = Vec<Cert>; type PrivateKeyData = Vec<Cert>;
@ -453,7 +444,7 @@ impl<P: PromptHandler> Format for OpenPGP<P> {
&self, &self,
private_keys: Option<Self::PrivateKeyData>, private_keys: Option<Self::PrivateKeyData>,
encrypted_data: &[Self::EncryptedData], encrypted_data: &[Self::EncryptedData],
prompt: Arc<Mutex<impl PromptHandler>>, prompt: Rc<Mutex<Box<dyn PromptHandler>>>,
) -> std::result::Result<(Vec<Share>, u8), Self::Error> { ) -> std::result::Result<(Vec<Share>, u8), Self::Error> {
// Be as liberal as possible when decrypting. // Be as liberal as possible when decrypting.
// We don't want to invalidate someone's keys just because the old sig expired. // We don't want to invalidate someone's keys just because the old sig expired.
@ -514,7 +505,7 @@ impl<P: PromptHandler> Format for OpenPGP<P> {
&self, &self,
private_keys: Option<Self::PrivateKeyData>, private_keys: Option<Self::PrivateKeyData>,
encrypted_data: &[Self::EncryptedData], encrypted_data: &[Self::EncryptedData],
prompt: Arc<Mutex<impl PromptHandler>>, prompt: Rc<Mutex<Box<dyn PromptHandler>>>,
) -> std::result::Result<(Share, u8), Self::Error> { ) -> std::result::Result<(Share, u8), Self::Error> {
let policy = NullPolicy::new(); let policy = NullPolicy::new();
@ -560,22 +551,22 @@ impl<P: PromptHandler> Format for OpenPGP<P> {
} }
} }
impl<P: PromptHandler> KeyDiscovery<OpenPGP<P>> for &Path { impl KeyDiscovery<OpenPGP> for &Path {
fn discover_public_keys(&self) -> Result<Vec<<OpenPGP<P> as Format>::PublicKey>> { fn discover_public_keys(&self) -> Result<Vec<<OpenPGP as Format>::PublicKey>> {
OpenPGP::<P>::discover_certs(self) OpenPGP::discover_certs(self)
} }
fn discover_private_keys(&self) -> Result<<OpenPGP<P> as Format>::PrivateKeyData> { fn discover_private_keys(&self) -> Result<<OpenPGP as Format>::PrivateKeyData> {
OpenPGP::<P>::discover_certs(self) OpenPGP::discover_certs(self)
} }
} }
impl<P: PromptHandler> KeyDiscovery<OpenPGP<P>> for &[Cert] { impl KeyDiscovery<OpenPGP> for &[Cert] {
fn discover_public_keys(&self) -> Result<Vec<<OpenPGP<P> as Format>::PublicKey>> { fn discover_public_keys(&self) -> Result<Vec<<OpenPGP as Format>::PublicKey>> {
Ok(self.to_vec()) Ok(self.to_vec())
} }
fn discover_private_keys(&self) -> Result<<OpenPGP<P> as Format>::PrivateKeyData> { fn discover_private_keys(&self) -> Result<<OpenPGP as Format>::PrivateKeyData> {
Ok(self.to_vec()) Ok(self.to_vec())
} }
} }
@ -637,12 +628,12 @@ fn decode_metadata_v1(buf: &[u8]) -> Result<(u8, Cert, Vec<Cert>)> {
// NOTE: When using single-decryptor mechanism, use this method with `threshold = 1` to return a // NOTE: When using single-decryptor mechanism, use this method with `threshold = 1` to return a
// single message. // single message.
fn decrypt_with_manager<P: PromptHandler>( fn decrypt_with_manager(
threshold: u8, threshold: u8,
messages: &mut HashMap<KeyID, EncryptedMessage>, messages: &mut HashMap<KeyID, EncryptedMessage>,
certs: &[Cert], certs: &[Cert],
policy: &dyn Policy, policy: &dyn Policy,
manager: &mut SmartcardManager<P>, manager: &mut SmartcardManager,
) -> Result<HashMap<KeyID, Vec<u8>>> { ) -> Result<HashMap<KeyID, Vec<u8>>> {
let mut decrypted_messages = HashMap::new(); let mut decrypted_messages = HashMap::new();
@ -687,11 +678,11 @@ fn decrypt_with_manager<P: PromptHandler>(
// NOTE: When using single-decryptor mechanism, only a single key should be provided in Keyring to // NOTE: When using single-decryptor mechanism, only a single key should be provided in Keyring to
// decrypt messages with. // decrypt messages with.
fn decrypt_with_keyring<P: PromptHandler>( fn decrypt_with_keyring(
messages: &mut HashMap<KeyID, EncryptedMessage>, messages: &mut HashMap<KeyID, EncryptedMessage>,
certs: &[Cert], certs: &[Cert],
policy: &NullPolicy, policy: &NullPolicy,
keyring: &mut Keyring<P>, keyring: &mut Keyring,
) -> Result<HashMap<KeyID, Vec<u8>>, Error> { ) -> Result<HashMap<KeyID, Vec<u8>>, Error> {
let mut decrypted_messages = HashMap::new(); let mut decrypted_messages = HashMap::new();
@ -721,11 +712,11 @@ fn decrypt_with_keyring<P: PromptHandler>(
Ok(decrypted_messages) Ok(decrypted_messages)
} }
fn decrypt_metadata<P: PromptHandler>( fn decrypt_metadata(
message: &EncryptedMessage, message: &EncryptedMessage,
policy: &NullPolicy, policy: &NullPolicy,
keyring: &mut Keyring<P>, keyring: &mut Keyring,
manager: &mut SmartcardManager<P>, manager: &mut SmartcardManager,
) -> Result<Vec<u8>> { ) -> Result<Vec<u8>> {
Ok(if keyring.is_empty() { Ok(if keyring.is_empty() {
manager.load_any_card()?; manager.load_any_card()?;

View File

@ -1,6 +1,6 @@
#![allow(clippy::expect_fun_call)] #![allow(clippy::expect_fun_call)]
use std::sync::{Arc, Mutex}; use std::{rc::Rc, sync::Mutex};
use keyfork_bug::{bug, POISONED_MUTEX}; use keyfork_bug::{bug, POISONED_MUTEX};
use keyfork_prompt::{Error as PromptError, PromptHandler}; use keyfork_prompt::{Error as PromptError, PromptHandler};
@ -27,14 +27,14 @@ pub enum Error {
pub type Result<T, E = Error> = std::result::Result<T, E>; pub type Result<T, E = Error> = std::result::Result<T, E>;
pub struct Keyring<P: PromptHandler> { pub struct Keyring {
full_certs: Vec<Cert>, full_certs: Vec<Cert>,
root: Option<Cert>, root: Option<Cert>,
pm: Arc<Mutex<P>>, pm: Rc<Mutex<Box<dyn PromptHandler>>>,
} }
impl<P: PromptHandler> Keyring<P> { impl Keyring {
pub fn new(certs: impl AsRef<[Cert]>, p: Arc<Mutex<P>>) -> Result<Self> { pub fn new(certs: impl AsRef<[Cert]>, p: Rc<Mutex<Box<dyn PromptHandler>>>) -> Result<Self> {
Ok(Self { Ok(Self {
full_certs: certs.as_ref().to_vec(), full_certs: certs.as_ref().to_vec(),
root: Default::default(), root: Default::default(),
@ -62,7 +62,7 @@ impl<P: PromptHandler> Keyring<P> {
} }
} }
impl<P: PromptHandler> VerificationHelper for &mut Keyring<P> { impl VerificationHelper for &mut Keyring {
fn get_certs(&mut self, ids: &[KeyHandle]) -> openpgp::Result<Vec<Cert>> { fn get_certs(&mut self, ids: &[KeyHandle]) -> openpgp::Result<Vec<Cert>> {
Ok(ids Ok(ids
.iter() .iter()
@ -108,7 +108,7 @@ impl<P: PromptHandler> VerificationHelper for &mut Keyring<P> {
} }
} }
impl<P: PromptHandler> DecryptionHelper for &mut Keyring<P> { impl DecryptionHelper for &mut Keyring {
fn decrypt<D>( fn decrypt<D>(
&mut self, &mut self,
pkesks: &[PKESK], pkesks: &[PKESK],

View File

@ -2,7 +2,8 @@
use std::{ use std::{
collections::{HashMap, HashSet}, collections::{HashMap, HashSet},
sync::{Arc, Mutex}, rc::Rc,
sync::Mutex,
}; };
use keyfork_bug::{bug, POISONED_MUTEX}; use keyfork_bug::{bug, POISONED_MUTEX};
@ -72,15 +73,15 @@ fn format_name(input: impl AsRef<str>) -> String {
} }
#[allow(clippy::module_name_repetitions)] #[allow(clippy::module_name_repetitions)]
pub struct SmartcardManager<P: PromptHandler> { pub struct SmartcardManager {
current_card: Option<Card<Open>>, current_card: Option<Card<Open>>,
root: Option<Cert>, root: Option<Cert>,
pm: Arc<Mutex<P>>, pm: Rc<Mutex<Box<dyn PromptHandler>>>,
pin_cache: HashMap<Fingerprint, String>, pin_cache: HashMap<Fingerprint, String>,
} }
impl<P: PromptHandler> SmartcardManager<P> { impl SmartcardManager {
pub fn new(p: Arc<Mutex<P>>) -> Result<Self> { pub fn new(p: Rc<Mutex<Box<dyn PromptHandler>>>) -> Result<Self> {
Ok(Self { Ok(Self {
current_card: None, current_card: None,
root: None, root: None,
@ -174,7 +175,7 @@ impl<P: PromptHandler> SmartcardManager<P> {
} }
} }
impl<P: PromptHandler> VerificationHelper for &mut SmartcardManager<P> { impl VerificationHelper for &mut SmartcardManager {
fn get_certs(&mut self, ids: &[openpgp::KeyHandle]) -> openpgp::Result<Vec<Cert>> { fn get_certs(&mut self, ids: &[openpgp::KeyHandle]) -> openpgp::Result<Vec<Cert>> {
#[allow(clippy::flat_map_option)] #[allow(clippy::flat_map_option)]
Ok(ids Ok(ids
@ -218,7 +219,7 @@ impl<P: PromptHandler> VerificationHelper for &mut SmartcardManager<P> {
} }
} }
impl<P: PromptHandler> DecryptionHelper for &mut SmartcardManager<P> { impl DecryptionHelper for &mut SmartcardManager {
fn decrypt<D>( fn decrypt<D>(
&mut self, &mut self,
pkesks: &[PKESK], pkesks: &[PKESK],
@ -277,7 +278,7 @@ impl<P: PromptHandler> DecryptionHelper for &mut SmartcardManager<P> {
format!("Unlock card {card_id} ({cardholder_name})\n{rpea}: {attempts}\n\nPIN: ") format!("Unlock card {card_id} ({cardholder_name})\n{rpea}: {attempts}\n\nPIN: ")
}; };
let mut prompt = self.pm.lock().expect(bug!(POISONED_MUTEX)); let mut prompt = self.pm.lock().expect(bug!(POISONED_MUTEX));
let temp_pin = prompt_validated_passphrase(&mut *prompt, &message, 3, &pin_validator)?; let temp_pin = prompt_validated_passphrase(&mut **prompt, &message, 3, &pin_validator)?;
let verification_status = transaction.verify_user_pin(temp_pin.as_str().trim()); let verification_status = transaction.verify_user_pin(temp_pin.as_str().trim());
match verification_status { match verification_status {
#[allow(clippy::ignored_unit_patterns)] #[allow(clippy::ignored_unit_patterns)]

View File

@ -4,12 +4,11 @@ use std::path::PathBuf;
use keyfork_mnemonic::{English, Mnemonic}; use keyfork_mnemonic::{English, Mnemonic};
use keyfork_prompt::{ use keyfork_prompt::{
default_terminal, prompt_validated_wordlist, default_handler, prompt_validated_wordlist,
validators::{ validators::{
mnemonic::{MnemonicChoiceValidator, WordLength}, mnemonic::{MnemonicChoiceValidator, WordLength},
Validator, Validator,
}, },
DefaultTerminal,
}; };
use keyfork_shard::{remote_decrypt, Format}; use keyfork_shard::{remote_decrypt, Format};
@ -42,8 +41,8 @@ impl RecoverSubcommands {
} => { } => {
let content = std::fs::read_to_string(shard_file)?; let content = std::fs::read_to_string(shard_file)?;
if content.contains("BEGIN PGP MESSAGE") { if content.contains("BEGIN PGP MESSAGE") {
let openpgp = keyfork_shard::openpgp::OpenPGP::<DefaultTerminal>::new(); let openpgp = keyfork_shard::openpgp::OpenPGP;
let prompt_handler = default_terminal()?; let prompt_handler = default_handler()?;
// TODO: remove .clone() by making handle() consume self // TODO: remove .clone() by making handle() consume self
let seed = openpgp.decrypt_all_shards_to_secret( let seed = openpgp.decrypt_all_shards_to_secret(
key_discovery.as_deref(), key_discovery.as_deref(),
@ -61,12 +60,12 @@ impl RecoverSubcommands {
Ok(seed) Ok(seed)
} }
RecoverSubcommands::Mnemonic {} => { RecoverSubcommands::Mnemonic {} => {
let mut term = default_terminal()?; let mut prompt_handler = default_handler()?;
let validator = MnemonicChoiceValidator { let validator = MnemonicChoiceValidator {
word_lengths: [WordLength::Count(12), WordLength::Count(24)], word_lengths: [WordLength::Count(12), WordLength::Count(24)],
}; };
let mnemonic = prompt_validated_wordlist::<English, _>( let mnemonic = prompt_validated_wordlist::<English, _>(
&mut term, &mut *prompt_handler,
"Mnemonic: ", "Mnemonic: ",
3, 3,
&*validator.to_fn(), &*validator.to_fn(),

View File

@ -1,6 +1,6 @@
use super::Keyfork; use super::Keyfork;
use clap::{builder::PossibleValue, Parser, Subcommand, ValueEnum}; use clap::{builder::PossibleValue, Parser, Subcommand, ValueEnum};
use keyfork_prompt::{default_terminal, DefaultTerminal}; use keyfork_prompt::default_handler;
use keyfork_shard::Format as _; use keyfork_shard::Format as _;
use std::{ use std::{
io::{stdin, stdout, Read, Write}, io::{stdin, stdout, Read, Write},
@ -64,7 +64,7 @@ impl ShardExec for OpenPGP {
secret: &[u8], secret: &[u8],
output: &mut (impl Write + Send + Sync), output: &mut (impl Write + Send + Sync),
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
let opgp = keyfork_shard::openpgp::OpenPGP::<DefaultTerminal>::new(); let opgp = keyfork_shard::openpgp::OpenPGP;
opgp.shard_and_encrypt(threshold, max, secret, key_discovery, output) opgp.shard_and_encrypt(threshold, max, secret, key_discovery, output)
} }
@ -74,8 +74,8 @@ impl ShardExec for OpenPGP {
input: impl Read + Send + Sync, input: impl Read + Send + Sync,
output: &mut impl Write, output: &mut impl Write,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
let openpgp = keyfork_shard::openpgp::OpenPGP::<DefaultTerminal>::new(); let openpgp = keyfork_shard::openpgp::OpenPGP;
let prompt = default_terminal()?; let prompt = default_handler()?;
let bytes = openpgp.decrypt_all_shards_to_secret(key_discovery, input, prompt)?; let bytes = openpgp.decrypt_all_shards_to_secret(key_discovery, input, prompt)?;
write!(output, "{}", smex::encode(bytes))?; write!(output, "{}", smex::encode(bytes))?;
@ -87,8 +87,8 @@ impl ShardExec for OpenPGP {
key_discovery: Option<&Path>, key_discovery: Option<&Path>,
input: impl Read + Send + Sync, input: impl Read + Send + Sync,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
let openpgp = keyfork_shard::openpgp::OpenPGP::<DefaultTerminal>::new(); let openpgp = keyfork_shard::openpgp::OpenPGP;
let prompt = default_terminal()?; let prompt = default_handler()?;
openpgp.decrypt_one_shard_for_transport(key_discovery, input, prompt)?; openpgp.decrypt_one_shard_for_transport(key_discovery, input, prompt)?;
Ok(()) Ok(())
} }

View File

@ -20,9 +20,10 @@ use keyfork_derive_path_data::paths;
use keyfork_derive_util::DerivationIndex; use keyfork_derive_util::DerivationIndex;
use keyfork_mnemonic::Mnemonic; use keyfork_mnemonic::Mnemonic;
use keyfork_prompt::{ use keyfork_prompt::{
default_terminal, prompt_validated_passphrase, default_handler,
prompt_validated_passphrase,
validators::{SecurePinValidator, Validator}, validators::{SecurePinValidator, Validator},
DefaultTerminal, Message, PromptHandler, Message,
}; };
use keyfork_shard::{openpgp::OpenPGP, Format}; use keyfork_shard::{openpgp::OpenPGP, Format};
@ -174,7 +175,7 @@ impl WizardSubcommands {
impl GenerateShardSecret { impl GenerateShardSecret {
fn handle(&self) -> Result<()> { fn handle(&self) -> Result<()> {
let seed = keyfork_entropy::generate_entropy_of_const_size::<{ 256 / 8 }>()?; let seed = keyfork_entropy::generate_entropy_of_const_size::<{ 256 / 8 }>()?;
let mut pm = default_terminal()?; let mut pm = default_handler()?;
let mut certs = vec![]; let mut certs = vec![];
let mut seen_cards: HashSet<String> = HashSet::new(); let mut seen_cards: HashSet<String> = HashSet::new();
let stdout = std::io::stdout(); let stdout = std::io::stdout();
@ -214,13 +215,13 @@ impl GenerateShardSecret {
))?; ))?;
}; };
let user_pin = prompt_validated_passphrase( let user_pin = prompt_validated_passphrase(
&mut pm, &mut *pm,
"Please enter the new smartcard User PIN: ", "Please enter the new smartcard User PIN: ",
3, 3,
&user_pin_validator, &user_pin_validator,
)?; )?;
let admin_pin = prompt_validated_passphrase( let admin_pin = prompt_validated_passphrase(
&mut pm, &mut *pm,
"Please enter the new smartcard Admin PIN: ", "Please enter the new smartcard Admin PIN: ",
3, 3,
&admin_pin_validator, &admin_pin_validator,
@ -236,7 +237,7 @@ impl GenerateShardSecret {
certs.push(cert); certs.push(cert);
} }
let opgp = OpenPGP::<DefaultTerminal>::new(); let opgp = OpenPGP;
if let Some(output_file) = self.output.as_ref() { if let Some(output_file) = self.output.as_ref() {
let output = File::create(output_file)?; let output = File::create(output_file)?;
@ -284,8 +285,8 @@ impl BottomsUp {
cert.serialize(&mut w)?; cert.serialize(&mut w)?;
w.finalize()?; w.finalize()?;
let opgp = OpenPGP::<DefaultTerminal>::new(); let opgp = OpenPGP;
let certs = OpenPGP::<DefaultTerminal>::discover_certs(&self.key_discovery)?; let certs = OpenPGP::discover_certs(&self.key_discovery)?;
let shardfile = File::create(&self.output_shardfile)?; let shardfile = File::create(&self.output_shardfile)?;
opgp.shard_and_encrypt( opgp.shard_and_encrypt(