use std::time::SystemTime;
use anyhow::{Context, Result, bail};
use ed25519_dalek::pkcs8::DecodePublicKey;
use sha2::{Digest, Sha256};
use crate::pgp;
pub enum PubKey {
Pgp(Box<pgp::Cert>),
Ed25519(ed25519_dalek::VerifyingKey),
P256(p256::ecdsa::VerifyingKey),
}
impl PubKey {
pub fn fingerprint(&self) -> String {
match self {
PubKey::Pgp(c) => c.fingerprint.clone(),
PubKey::Ed25519(k) => spki_fingerprint(k),
PubKey::P256(k) => spki_fingerprint(k),
}
}
pub fn all_fingerprints(&self) -> Vec<String> {
match self {
PubKey::Pgp(c) => c.all_fingerprints(),
_ => vec![self.fingerprint()],
}
}
pub fn kind(&self) -> &'static str {
match self {
PubKey::Pgp(_) => "OpenPGP",
PubKey::Ed25519(_) => "Ed25519",
PubKey::P256(_) => "ECDSA P-256",
}
}
pub fn label(&self) -> Option<&str> {
match self {
PubKey::Pgp(c) => c.user_ids.first().map(String::as_str),
_ => None,
}
}
pub fn validity(&self, now: SystemTime) -> String {
match self {
PubKey::Pgp(c) if c.revoked => "REVOKED".into(),
PubKey::Pgp(c) => match c.expires {
Some(e) if e <= now => format!("expired {}", crate::date(e)),
Some(e) => format!("expires {}", crate::date(e)),
None => "no expiry".into(),
},
_ => "no expiry".into(),
}
}
}
fn spki_fingerprint(k: &impl ed25519_dalek::pkcs8::EncodePublicKey) -> String {
match k.to_public_key_der() {
Ok(der) => hex::encode(Sha256::digest(der.as_bytes())),
Err(_) => String::from("?"),
}
}
pub fn parse(data: &[u8]) -> Result<Vec<PubKey>> {
let text = std::str::from_utf8(data).unwrap_or("");
if text.contains("-----BEGIN PUBLIC KEY-----") {
let mut keys = Vec::new();
for block in pem_blocks(text, "PUBLIC KEY") {
if let Ok(k) = ed25519_dalek::VerifyingKey::from_public_key_pem(&block) {
keys.push(PubKey::Ed25519(k));
} else if let Ok(k) = p256::ecdsa::VerifyingKey::from_public_key_pem(&block) {
keys.push(PubKey::P256(k));
} else {
bail!("a public key that is neither Ed25519 nor ECDSA P-256");
}
}
return Ok(keys);
}
let certs = pgp::parse_certs(data).context("not an OpenPGP key, nor a PEM public key")?;
Ok(certs
.into_iter()
.map(|c| PubKey::Pgp(Box::new(c)))
.collect())
}
pub fn pem_blocks(text: &str, label: &str) -> Vec<String> {
let begin = format!("-----BEGIN {label}-----");
let end = format!("-----END {label}-----");
let mut out = Vec::new();
let mut rest = text;
while let Some(b) = rest.find(&begin) {
let Some(e) = rest[b..].find(&end) else { break };
let stop = b + e + end.len();
out.push(format!("{}\n", &rest[b..stop]));
rest = &rest[stop..];
}
out
}