librage 1.1.0

A safe, simple, and complete Rust wrapper for the rage (age) encryption library.
Documentation
use crate::handler::error::LibrageError;
use age::{
    secrecy::SecretString,
    ssh::{self, Identity as SshIdentity, ParseRecipientKeyError},
    x25519,
};
use std::io::BufReader;

pub(crate) fn parse_x25519_recipient(key: &str) -> Result<Box<dyn age::Recipient>, LibrageError> {
    key.parse::<x25519::Recipient>()
        .map(|r| Box::new(r) as Box<dyn age::Recipient>)
        .map_err(|e: &'static str| LibrageError::InvalidPublicKey(e.to_string()))
}

pub(crate) fn parse_x25519_recipients(
    keys: &[&str],
) -> Result<Vec<Box<dyn age::Recipient>>, LibrageError> {
    keys.iter().map(|k| parse_x25519_recipient(k)).collect()
}

pub(crate) fn parse_ssh_recipient(key: &str) -> Result<Box<dyn age::Recipient>, LibrageError> {
    key.parse::<ssh::Recipient>()
        .map(|r| Box::new(r) as Box<dyn age::Recipient>)
        .map_err(|e: ParseRecipientKeyError| LibrageError::InvalidSshKey(format!("{:?}", e)))
}

pub(crate) fn parse_ssh_identity(
    key_data: &str,
    passphrase: Option<&str>,
) -> Result<Box<dyn age::Identity>, LibrageError> {
    let reader = BufReader::new(key_data.as_bytes());
    let ssh_identity = SshIdentity::from_buffer(reader, None)
        .map_err(|e| LibrageError::InvalidSshKey(e.to_string()))?;

    match passphrase {
        Some(pass) => match ssh_identity {
            SshIdentity::Encrypted(enc) => {
                let pass_secret = SecretString::new(pass.to_owned().into());
                let unenc = enc
                    .decrypt(pass_secret)
                    .map_err(|e| LibrageError::InvalidSshKey(e.to_string()))?;
                Ok(Box::new(SshIdentity::Unencrypted(unenc)) as Box<dyn age::Identity>)
            }
            other => Ok(Box::new(other) as Box<dyn age::Identity>),
        },
        None => Ok(Box::new(ssh_identity) as Box<dyn age::Identity>),
    }
}