use pgp::composed::{Esk, Message, SignedSecretKey};
use pgp::packet::PublicKeyEncryptedSessionKey;
use pgp::types::Password;
use crate::shared::{EXIT_AUTH, EXIT_NOT_FOR_US, Failure, Result};
fn auth(detail: impl std::fmt::Display) -> Failure {
Failure::new(
EXIT_AUTH,
format!("authentication failed: message is tampered, truncated, or malformed ({detail})"),
)
}
fn parse(input: &[u8]) -> Result<Message<'_>> {
let armored = input.trim_ascii_start().starts_with(b"-----BEGIN");
let parsed = if armored {
Message::from_armor(input).map(|(msg, _)| msg)
} else {
Message::from_bytes(input)
};
parsed.map_err(|_| Failure::new(EXIT_AUTH, "not a valid PGP message"))
}
fn addressed_to(msg: &Message<'_>, key: &SignedSecretKey) -> bool {
let Message::Encrypted { esk, .. } = msg else {
return false;
};
esk.iter().any(|esk| match esk {
Esk::PublicKeyEncryptedSessionKey(pkesk) => matches_key(pkesk, key),
Esk::SymKeyEncryptedSessionKey(_) => false,
})
}
fn matches_key(pkesk: &PublicKeyEncryptedSessionKey, key: &SignedSecretKey) -> bool {
pkesk.match_identity(&key.primary_key.public_key())
|| key
.secret_subkeys
.iter()
.any(|sub| pkesk.match_identity(&sub.key.public_key()))
}
pub fn decrypt(key: &SignedSecretKey, input: &[u8]) -> Result<Vec<u8>> {
if input.trim_ascii().is_empty() {
return Err(Failure::usage("no message given"));
}
let msg = parse(input)?;
if !msg.is_encrypted() {
return Err(Failure::new(
EXIT_NOT_FOR_US,
"message is not encrypted for this key",
));
}
if !addressed_to(&msg, key) {
return Err(Failure::new(
EXIT_NOT_FOR_US,
"message is not encrypted for this key",
));
}
let mut msg = msg.decrypt(&Password::empty(), key).map_err(auth)?;
if msg.is_compressed() {
return Err(Failure::new(
EXIT_AUTH,
"compressed messages are not supported",
));
}
msg.as_data_vec().map_err(auth)
}