use std::fmt;
use std::str::FromStr;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use ed25519_dalek::{Signature, Signer as _};
use crate::error::{RejectKind, Rejection};
#[derive(Clone)]
pub struct SigningKey(ed25519_dalek::SigningKey);
impl SigningKey {
#[must_use]
pub fn from_seed(seed: &[u8; 32]) -> Self {
Self(ed25519_dalek::SigningKey::from_bytes(seed))
}
pub fn from_libsodium_secret(secret: &[u8; 64]) -> Result<Self, Rejection> {
ed25519_dalek::SigningKey::from_keypair_bytes(secret)
.map(Self)
.map_err(|_| {
Rejection::new(
RejectKind::Signature,
"[UFTP App. 4 §1] crypto_sign_keypair",
"The public half of the secret key does not match its seed.",
)
})
}
#[must_use]
pub fn verifying_key(&self) -> VerifyingKey {
VerifyingKey(self.0.verifying_key())
}
#[must_use]
pub fn public_keys(&self, encryption_key: [u8; 32]) -> PublicKeys {
PublicKeys {
signing: self.verifying_key(),
encryption: encryption_key,
}
}
pub(crate) fn seal(&self, message: &[u8]) -> Vec<u8> {
let signature: Signature = self.0.sign(message);
let mut sealed = Vec::with_capacity(64 + message.len());
sealed.extend_from_slice(&signature.to_bytes());
sealed.extend_from_slice(message);
sealed
}
}
impl fmt::Debug for SigningKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SigningKey(<redacted>)")
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct VerifyingKey(ed25519_dalek::VerifyingKey);
impl VerifyingKey {
pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, Rejection> {
let key = ed25519_dalek::VerifyingKey::from_bytes(bytes)
.map_err(|_| bad_key("The signing key is not a valid Ed25519 public key."))?;
if key.is_weak() {
return Err(bad_key(
"The signing key has small order and would accept forged signatures.",
));
}
Ok(Self(key))
}
#[must_use]
pub fn to_bytes(&self) -> [u8; 32] {
self.0.to_bytes()
}
pub(crate) fn open<'a>(&self, sealed: &'a [u8]) -> Result<&'a [u8], Rejection> {
let invalid = || {
Rejection::new(
RejectKind::Signature,
"[UFTP App. 4 §4] invalid signature",
"The body does not verify under the sender's public signing key.",
)
};
if sealed.len() < 64 {
return Err(invalid());
}
let (sig, message) = sealed.split_at(64);
let signature = Signature::from_slice(sig).map_err(|_| invalid())?;
self.0
.verify_strict(message, &signature)
.map_err(|_| invalid())?;
Ok(message)
}
}
impl fmt::Debug for VerifyingKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "VerifyingKey({})", STANDARD.encode(self.0.to_bytes()))
}
}
fn bad_key(message: &str) -> Rejection {
Rejection::new(
RejectKind::KeyLookup,
"[UFTP App. 4 §1] CS1 public key",
message,
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PublicKeys {
signing: VerifyingKey,
encryption: [u8; 32],
}
impl PublicKeys {
#[must_use]
pub fn signing(&self) -> &VerifyingKey {
&self.signing
}
#[must_use]
pub fn encryption(&self) -> &[u8; 32] {
&self.encryption
}
}
impl FromStr for PublicKeys {
type Err = Rejection;
fn from_str(s: &str) -> Result<Self, Rejection> {
let b64 = s
.strip_prefix("cs1.")
.ok_or_else(|| bad_key("A CS1 public key starts with `cs1.`."))?;
let bytes = STANDARD
.decode(b64)
.map_err(|_| bad_key("The CS1 public key is not valid Base64."))?;
let bytes: [u8; 64] = bytes.try_into().map_err(|v: Vec<u8>| {
bad_key(&format!(
"A CS1 public key is 64 bytes (signing key and encryption key); this one is {}.",
v.len()
))
})?;
let mut signing = [0u8; 32];
let mut encryption = [0u8; 32];
signing.copy_from_slice(&bytes[..32]);
encryption.copy_from_slice(&bytes[32..]);
Ok(Self {
signing: VerifyingKey::from_bytes(&signing)?,
encryption,
})
}
}
impl fmt::Display for PublicKeys {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut bytes = [0u8; 64];
bytes[..32].copy_from_slice(&self.signing.to_bytes());
bytes[32..].copy_from_slice(&self.encryption);
write!(f, "cs1.{}", STANDARD.encode(bytes))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn spec_example_key_is_not_a_valid_point() {
let s = "cs1.V4lZrkYHq8FzneXxUML+QEMXMul3tBm+gPGoVDIZBA92VoWTu8/kRu2Zx72XOm1i/qwwoSgXjqSAqSa43myCaQ==";
let e = s.parse::<PublicKeys>().unwrap_err();
assert!(e.message().contains("not a valid Ed25519 public key"));
}
#[test]
fn public_keys_print_and_parse() {
let keys = SigningKey::from_seed(&[9; 32]).public_keys([5; 32]);
let s = keys.to_string();
assert!(s.starts_with("cs1."));
assert_eq!(s.parse::<PublicKeys>().unwrap(), keys);
}
#[test]
fn wrong_prefix_and_length_refused() {
assert!(
"cs2.AAAA"
.parse::<PublicKeys>()
.unwrap_err()
.message()
.contains("cs1.")
);
let short = format!("cs1.{}", STANDARD.encode([1u8; 63]));
assert!(
short
.parse::<PublicKeys>()
.unwrap_err()
.message()
.contains("63")
);
}
#[test]
fn seal_then_open() {
let k = SigningKey::from_seed(&[7; 32]);
let sealed = k.seal(b"hello");
assert_eq!(sealed.len(), 69);
assert_eq!(k.verifying_key().open(&sealed).unwrap(), b"hello");
let mut tampered = sealed.clone();
tampered[66] ^= 1;
assert_eq!(
k.verifying_key().open(&tampered).unwrap_err().http_status(),
401
);
}
#[test]
fn debug_redacts() {
let k = SigningKey::from_seed(&[7; 32]);
assert_eq!(format!("{k:?}"), "SigningKey(<redacted>)");
}
}