use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use crate::error::{CoreError, Result};
use crate::multikey;
pub const ED25519_SEED_LEN: usize = 32;
pub const ED25519_PUBLIC_LEN: usize = 32;
pub const ED25519_SIGNATURE_LEN: usize = 64;
pub struct Ed25519KeyPair {
signing: SigningKey,
}
impl Ed25519KeyPair {
pub fn generate() -> Result<Self> {
let mut seed = [0u8; ED25519_SEED_LEN];
getrandom::getrandom(&mut seed).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?;
Ok(Self::from_seed(&seed))
}
pub fn from_seed(seed: &[u8; ED25519_SEED_LEN]) -> Self {
Self {
signing: SigningKey::from_bytes(seed),
}
}
pub fn from_seed_slice(seed: &[u8]) -> Result<Self> {
let arr: [u8; ED25519_SEED_LEN] =
seed.try_into().map_err(|_| CoreError::InvalidKeyLength {
expected: ED25519_SEED_LEN,
got: seed.len(),
})?;
Ok(Self::from_seed(&arr))
}
pub fn seed(&self) -> [u8; ED25519_SEED_LEN] {
self.signing.to_bytes()
}
pub fn public_key(&self) -> [u8; ED25519_PUBLIC_LEN] {
self.signing.verifying_key().to_bytes()
}
pub fn sign(&self, message: &[u8]) -> [u8; ED25519_SIGNATURE_LEN] {
self.signing.sign(message).to_bytes()
}
pub fn public_multikey(&self) -> String {
multikey::encode_ed25519_public(&self.public_key()).expect("public key is always 32 bytes")
}
pub fn did_key(&self) -> String {
ed25519_to_did_key(&self.public_key()).expect("public key is always 32 bytes")
}
}
const FIELD_PRIME_LE: [u8; 32] = [
0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
];
pub fn is_canonical_point_encoding(encoded: &[u8; 32]) -> bool {
let mut y = *encoded;
y[31] &= 0x7f; for i in (0..32).rev() {
if y[i] != FIELD_PRIME_LE[i] {
return y[i] < FIELD_PRIME_LE[i];
}
}
false }
pub fn strict_verifying_key(public_key: &[u8]) -> Result<VerifyingKey> {
let pk: [u8; ED25519_PUBLIC_LEN] =
public_key
.try_into()
.map_err(|_| CoreError::InvalidKeyLength {
expected: ED25519_PUBLIC_LEN,
got: public_key.len(),
})?;
if !is_canonical_point_encoding(&pk) {
return Err(CoreError::Crypto(
"bad public key: non-canonical point encoding".into(),
));
}
let vk = VerifyingKey::from_bytes(&pk)
.map_err(|e| CoreError::Crypto(format!("bad public key: {e}")))?;
if vk.is_weak() {
return Err(CoreError::Crypto(
"bad public key: small-order point".into(),
));
}
Ok(vk)
}
pub fn verify(public_key: &[u8], message: &[u8], signature: &[u8]) -> Result<bool> {
let sig: [u8; ED25519_SIGNATURE_LEN] =
signature
.try_into()
.map_err(|_| CoreError::InvalidSignatureLength {
expected: ED25519_SIGNATURE_LEN,
got: signature.len(),
})?;
let vk = strict_verifying_key(public_key)?;
let mut r = [0u8; 32];
r.copy_from_slice(&sig[..32]);
if !is_canonical_point_encoding(&r) {
return Ok(false);
}
Ok(vk
.verify_strict(message, &Signature::from_bytes(&sig))
.is_ok())
}
pub fn ed25519_to_did_key(public_key: &[u8]) -> Result<String> {
Ok(format!(
"did:key:{}",
multikey::encode_ed25519_public(public_key)?
))
}
pub fn did_key_to_ed25519(did: &str) -> Result<Vec<u8>> {
let mk = did
.strip_prefix("did:key:")
.ok_or_else(|| CoreError::InvalidDid("not a did:key".into()))?;
let decoded = multikey::decode(mk)?;
if decoded.algorithm != "Ed25519" {
return Err(CoreError::InvalidDid(format!(
"did:key is {} not Ed25519",
decoded.algorithm
)));
}
Ok(decoded.raw_key)
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
pub(crate) const SMALL_ORDER_ENCODINGS: [&str; 14] = [
"0000000000000000000000000000000000000000000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000080",
"0100000000000000000000000000000000000000000000000000000000000000",
"0100000000000000000000000000000000000000000000000000000000000080",
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
"ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
"ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
"edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
"edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
"eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
"eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
];
pub(crate) const NON_CANONICAL_ENCODINGS: [&str; 2] = [
"f0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
];
pub(crate) fn unhex32(h: &str) -> [u8; 32] {
let mut out = [0u8; 32];
for (i, b) in out.iter_mut().enumerate() {
*b = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).unwrap();
}
out
}
#[test]
fn small_order_public_keys_are_refused() {
for h in SMALL_ORDER_ENCODINGS {
let k = unhex32(h);
assert!(strict_verifying_key(&k).is_err(), "{h}");
let mut sig = [0u8; 64];
sig[..32].copy_from_slice(&k);
assert!(verify(&k, b"any message", &sig).is_err(), "{h}");
}
}
#[test]
fn non_canonical_public_keys_are_refused() {
for h in NON_CANONICAL_ENCODINGS {
let k = unhex32(h);
assert!(!is_canonical_point_encoding(&k));
assert!(VerifyingKey::from_bytes(&k).is_ok(), "{h} is a curve point");
assert!(strict_verifying_key(&k).is_err(), "{h}");
}
let mut three = [0u8; 32];
three[0] = 3;
assert!(strict_verifying_key(&three).is_ok());
assert!(is_canonical_point_encoding(&unhex32(
SMALL_ORDER_ENCODINGS[8]
)));
assert!(!is_canonical_point_encoding(&unhex32(
SMALL_ORDER_ENCODINGS[10]
)));
assert!(!is_canonical_point_encoding(&unhex32(
SMALL_ORDER_ENCODINGS[11]
)));
}
#[test]
fn small_order_or_non_canonical_r_is_refused() {
let kp = Ed25519KeyPair::from_seed(&[8u8; 32]);
let msg = b"vouch protocol";
let good = kp.sign(msg);
assert!(verify(&kp.public_key(), msg, &good).unwrap());
for h in SMALL_ORDER_ENCODINGS
.iter()
.chain(NON_CANONICAL_ENCODINGS.iter())
{
let mut sig = good;
sig[..32].copy_from_slice(&unhex32(h));
assert!(!verify(&kp.public_key(), msg, &sig).unwrap(), "R = {h}");
}
let l: [u8; 32] = [
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9,
0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x10,
];
let mut sig = good;
let mut carry = 0u16;
for i in 0..32 {
let v = u16::from(sig[32 + i]) + u16::from(l[i]) + carry;
sig[32 + i] = v as u8;
carry = v >> 8;
}
assert!(!verify(&kp.public_key(), msg, &sig).unwrap_or(false));
}
#[test]
fn sign_verify_roundtrip() {
let kp = Ed25519KeyPair::generate().unwrap();
let msg = b"vouch protocol";
let sig = kp.sign(msg);
assert!(verify(&kp.public_key(), msg, &sig).unwrap());
assert!(!verify(&kp.public_key(), b"tampered", &sig).unwrap());
}
#[test]
fn did_key_roundtrip() {
let kp = Ed25519KeyPair::generate().unwrap();
let did = kp.did_key();
assert!(did.starts_with("did:key:z6Mk"));
assert_eq!(did_key_to_ed25519(&did).unwrap(), kp.public_key().to_vec());
}
#[test]
fn seed_determinism() {
let seed = [3u8; 32];
let a = Ed25519KeyPair::from_seed(&seed);
let b = Ed25519KeyPair::from_seed(&seed);
assert_eq!(a.public_key(), b.public_key());
}
}