use base64::engine::general_purpose::STANDARD as B64;
use base64::Engine;
use blake2::{Blake2b512, Digest};
use crate::error::{KeepError, Result};
const KEY_ID_DOMAIN: &[u8] = b"keep-frost-ed25519-minisign-keyid-v1";
pub const ALG_LEGACY: [u8; 2] = *b"Ed";
pub const ALG_PREHASHED: [u8; 2] = *b"ED";
pub const MAX_COMMENT_LEN: usize = 1024;
pub fn validate_comment(field: &str, comment: &str) -> Result<()> {
if comment.len() > MAX_COMMENT_LEN {
return Err(KeepError::InvalidInput(format!(
"{field} comment exceeds {MAX_COMMENT_LEN} bytes"
)));
}
if comment.contains('\n') || comment.contains('\r') {
return Err(KeepError::InvalidInput(format!(
"{field} comment must not contain newline characters"
)));
}
Ok(())
}
pub fn key_id(group_pubkey: &[u8; 32]) -> [u8; 8] {
let mut hasher = Blake2b512::new();
hasher.update(KEY_ID_DOMAIN);
hasher.update(group_pubkey);
let digest = hasher.finalize();
let mut id = [0u8; 8];
id.copy_from_slice(&digest[..8]);
id
}
pub fn prehash(message: &[u8]) -> [u8; 64] {
let mut hasher = Blake2b512::new();
hasher.update(message);
let digest = hasher.finalize();
let mut out = [0u8; 64];
out.copy_from_slice(&digest);
out
}
pub fn global_signed_bytes(signature: &[u8; 64], trusted_comment: &str) -> Vec<u8> {
let mut buf = Vec::with_capacity(64 + trusted_comment.len());
buf.extend_from_slice(signature);
buf.extend_from_slice(trusted_comment.as_bytes());
buf
}
pub struct MinisignSignature {
pub sig_alg: [u8; 2],
pub key_id: [u8; 8],
pub signature: [u8; 64],
pub global_signature: [u8; 64],
pub untrusted_comment: String,
pub trusted_comment: String,
}
impl MinisignSignature {
pub fn encode(&self) -> Result<String> {
validate_comment("untrusted", &self.untrusted_comment)?;
validate_comment("trusted", &self.trusted_comment)?;
let mut sig_blob = Vec::with_capacity(2 + 8 + 64);
sig_blob.extend_from_slice(&self.sig_alg);
sig_blob.extend_from_slice(&self.key_id);
sig_blob.extend_from_slice(&self.signature);
Ok(format!(
"untrusted comment: {}\n{}\ntrusted comment: {}\n{}\n",
self.untrusted_comment,
B64.encode(&sig_blob),
self.trusted_comment,
B64.encode(self.global_signature),
))
}
pub fn parse(text: &str) -> Result<Self> {
let mut lines = text.lines();
let untrusted_comment = lines
.next()
.and_then(|l| l.strip_prefix("untrusted comment: "))
.ok_or_else(|| KeepError::InvalidInput("missing untrusted comment line".into()))?
.to_string();
validate_comment("untrusted", &untrusted_comment)?;
let sig_blob_b64 = lines
.next()
.ok_or_else(|| KeepError::InvalidInput("missing signature line".into()))?
.trim();
let sig_blob = B64
.decode(sig_blob_b64)
.map_err(|_| KeepError::InvalidInput("invalid base64 in signature line".into()))?;
if sig_blob.len() != 2 + 8 + 64 {
return Err(KeepError::InvalidInput(
"signature blob has wrong length".into(),
));
}
let mut sig_alg = [0u8; 2];
sig_alg.copy_from_slice(&sig_blob[..2]);
let mut key_id = [0u8; 8];
key_id.copy_from_slice(&sig_blob[2..10]);
let mut signature = [0u8; 64];
signature.copy_from_slice(&sig_blob[10..74]);
let trusted_comment = lines
.next()
.and_then(|l| l.strip_prefix("trusted comment: "))
.ok_or_else(|| KeepError::InvalidInput("missing trusted comment line".into()))?
.to_string();
validate_comment("trusted", &trusted_comment)?;
let global_b64 = lines
.next()
.ok_or_else(|| KeepError::InvalidInput("missing global signature line".into()))?
.trim();
let global = B64.decode(global_b64).map_err(|_| {
KeepError::InvalidInput("invalid base64 in global signature line".into())
})?;
if global.len() != 64 {
return Err(KeepError::InvalidInput(
"global signature has wrong length".into(),
));
}
let mut global_signature = [0u8; 64];
global_signature.copy_from_slice(&global);
if lines.any(|l| !l.trim().is_empty()) {
return Err(KeepError::InvalidInput(
"unexpected trailing content after signature".into(),
));
}
Ok(Self {
sig_alg,
key_id,
signature,
global_signature,
untrusted_comment,
trusted_comment,
})
}
}
pub struct MinisignPublicKey {
pub key_id: [u8; 8],
pub public_key: [u8; 32],
pub untrusted_comment: String,
}
impl MinisignPublicKey {
pub fn from_group_pubkey(group_pubkey: &[u8; 32], untrusted_comment: String) -> Self {
Self {
key_id: key_id(group_pubkey),
public_key: *group_pubkey,
untrusted_comment,
}
}
pub fn encode(&self) -> Result<String> {
validate_comment("untrusted", &self.untrusted_comment)?;
let mut blob = Vec::with_capacity(2 + 8 + 32);
blob.extend_from_slice(&ALG_LEGACY);
blob.extend_from_slice(&self.key_id);
blob.extend_from_slice(&self.public_key);
Ok(format!(
"untrusted comment: {}\n{}\n",
self.untrusted_comment,
B64.encode(&blob),
))
}
pub fn parse(text: &str) -> Result<Self> {
let mut lines = text.lines();
let untrusted_comment = lines
.next()
.and_then(|l| l.strip_prefix("untrusted comment: "))
.ok_or_else(|| KeepError::InvalidInput("missing untrusted comment line".into()))?
.to_string();
let blob_b64 = lines
.next()
.ok_or_else(|| KeepError::InvalidInput("missing public key line".into()))?
.trim();
let blob = B64
.decode(blob_b64)
.map_err(|_| KeepError::InvalidInput("invalid base64 in public key line".into()))?;
if blob.len() != 2 + 8 + 32 {
return Err(KeepError::InvalidInput(
"public key blob has wrong length".into(),
));
}
if blob[..2] != ALG_LEGACY {
return Err(KeepError::InvalidInput(
"unexpected public key algorithm".into(),
));
}
let mut key_id = [0u8; 8];
key_id.copy_from_slice(&blob[2..10]);
let mut public_key = [0u8; 32];
public_key.copy_from_slice(&blob[10..42]);
Ok(Self {
key_id,
public_key,
untrusted_comment,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn key_id_is_deterministic_and_stable() {
let pk = [7u8; 32];
assert_eq!(key_id(&pk), key_id(&pk));
let pk2 = [8u8; 32];
assert_ne!(key_id(&pk), key_id(&pk2));
}
#[test]
fn signature_round_trips() {
let sig = MinisignSignature {
sig_alg: ALG_PREHASHED,
key_id: [1, 2, 3, 4, 5, 6, 7, 8],
signature: [9u8; 64],
global_signature: [10u8; 64],
untrusted_comment: "signature from keep".to_string(),
trusted_comment: "timestamp:123\tfile:x".to_string(),
};
let encoded = sig.encode().unwrap();
let parsed = MinisignSignature::parse(&encoded).unwrap();
assert_eq!(parsed.sig_alg, sig.sig_alg);
assert_eq!(parsed.key_id, sig.key_id);
assert_eq!(parsed.signature, sig.signature);
assert_eq!(parsed.global_signature, sig.global_signature);
assert_eq!(parsed.untrusted_comment, sig.untrusted_comment);
assert_eq!(parsed.trusted_comment, sig.trusted_comment);
}
#[test]
fn pubkey_round_trips() {
let group_pubkey = [42u8; 32];
let pk = MinisignPublicKey::from_group_pubkey(&group_pubkey, "keep pubkey".to_string());
let encoded = pk.encode().unwrap();
let parsed = MinisignPublicKey::parse(&encoded).unwrap();
assert_eq!(parsed.key_id, key_id(&group_pubkey));
assert_eq!(parsed.public_key, group_pubkey);
assert_eq!(parsed.untrusted_comment, "keep pubkey");
}
}