Skip to main content

vouch_core/
keys.rs

1//! Ed25519 key generation, signing, verification, and did:key encoding.
2//!
3//! Matches the TypeScript reference SDK: the same seed produces the same public
4//! key, the same message produces the same 64-byte signature, and did:key uses
5//! the Ed25519 multikey (`did:key:z6Mk...`). Interop is asserted against the
6//! shared vectors (a seed -> public-key known-answer test).
7
8#[allow(unused_imports)]
9use crate::prelude::*;
10
11use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
12
13use crate::error::{CoreError, Result};
14use crate::multikey;
15
16pub const ED25519_SEED_LEN: usize = 32;
17pub const ED25519_PUBLIC_LEN: usize = 32;
18pub const ED25519_SIGNATURE_LEN: usize = 64;
19
20/// An Ed25519 key pair. The 32-byte seed is the private key (RFC 8032).
21pub struct Ed25519KeyPair {
22    signing: SigningKey,
23}
24
25impl Ed25519KeyPair {
26    /// Generate a fresh key pair using the platform CSPRNG (getrandom; on WASM
27    /// this is the JS crypto API via the getrandom "js" feature in the wasm
28    /// wrapper crate).
29    pub fn generate() -> Result<Self> {
30        let mut seed = [0u8; ED25519_SEED_LEN];
31        crate::random::fill(&mut seed).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?;
32        Ok(Self::from_seed(&seed))
33    }
34
35    /// Build a key pair from a 32-byte seed (deterministic; used for KATs and
36    /// for importing an existing private key).
37    pub fn from_seed(seed: &[u8; ED25519_SEED_LEN]) -> Self {
38        Self {
39            signing: SigningKey::from_bytes(seed),
40        }
41    }
42
43    /// Build a key pair from a seed slice, validating its length.
44    pub fn from_seed_slice(seed: &[u8]) -> Result<Self> {
45        let arr: [u8; ED25519_SEED_LEN] =
46            seed.try_into().map_err(|_| CoreError::InvalidKeyLength {
47                expected: ED25519_SEED_LEN,
48                got: seed.len(),
49            })?;
50        Ok(Self::from_seed(&arr))
51    }
52
53    /// The 32-byte private seed.
54    pub fn seed(&self) -> [u8; ED25519_SEED_LEN] {
55        self.signing.to_bytes()
56    }
57
58    /// The 32-byte public key.
59    pub fn public_key(&self) -> [u8; ED25519_PUBLIC_LEN] {
60        self.signing.verifying_key().to_bytes()
61    }
62
63    /// Sign a message, returning the 64-byte signature.
64    pub fn sign(&self, message: &[u8]) -> [u8; ED25519_SIGNATURE_LEN] {
65        self.signing.sign(message).to_bytes()
66    }
67
68    /// The public key as a Multikey string (z-prefixed base58btc).
69    pub fn public_multikey(&self) -> String {
70        multikey::encode_ed25519_public(&self.public_key()).expect("public key is always 32 bytes")
71    }
72
73    /// The did:key form of the public key.
74    pub fn did_key(&self) -> String {
75        ed25519_to_did_key(&self.public_key()).expect("public key is always 32 bytes")
76    }
77}
78
79/// The field prime p = 2^255 - 19, little-endian (the byte order of an encoded
80/// Ed25519 point).
81const FIELD_PRIME_LE: [u8; 32] = [
82    0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
83    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
84];
85
86/// True when a 32-byte Ed25519 point encoding is canonical: its y coordinate
87/// (the low 255 bits, little-endian) is below p. An encoding with y >= p names
88/// the same point as y - p, so accepting it would give one key two spellings.
89pub fn is_canonical_point_encoding(encoded: &[u8; 32]) -> bool {
90    let mut y = *encoded;
91    y[31] &= 0x7f; // drop the sign bit of x
92                   // Compare the little-endian numbers from the most significant byte down.
93    for i in (0..32).rev() {
94        if y[i] != FIELD_PRIME_LE[i] {
95            return y[i] < FIELD_PRIME_LE[i];
96        }
97    }
98    false // y == p
99}
100
101/// Decode a 32-byte Ed25519 public key strictly: the encoding must be
102/// canonical (y < p), must decode to a curve point, and the point must not be
103/// of small order (the identity or a torsion point, which lets one signature
104/// verify for many messages). Weak keys are refused here, at decode time, so
105/// they never reach a verifier.
106pub fn strict_verifying_key(public_key: &[u8]) -> Result<VerifyingKey> {
107    let pk: [u8; ED25519_PUBLIC_LEN] =
108        public_key
109            .try_into()
110            .map_err(|_| CoreError::InvalidKeyLength {
111                expected: ED25519_PUBLIC_LEN,
112                got: public_key.len(),
113            })?;
114    if !is_canonical_point_encoding(&pk) {
115        return Err(CoreError::Crypto(
116            "bad public key: non-canonical point encoding".into(),
117        ));
118    }
119    let vk = VerifyingKey::from_bytes(&pk)
120        .map_err(|e| CoreError::Crypto(format!("bad public key: {e}")))?;
121    if vk.is_weak() {
122        return Err(CoreError::Crypto(
123            "bad public key: small-order point".into(),
124        ));
125    }
126    Ok(vk)
127}
128
129/// Verify a 64-byte Ed25519 signature over a message against a 32-byte public key.
130///
131/// Strict in every part: the public key must pass [`strict_verifying_key`]
132/// (an `Err` otherwise), the signature's R must be the canonical encoding of a
133/// point that is not of small order, and S must be below the group order.
134pub fn verify(public_key: &[u8], message: &[u8], signature: &[u8]) -> Result<bool> {
135    let sig: [u8; ED25519_SIGNATURE_LEN] =
136        signature
137            .try_into()
138            .map_err(|_| CoreError::InvalidSignatureLength {
139                expected: ED25519_SIGNATURE_LEN,
140                got: signature.len(),
141            })?;
142    let vk = strict_verifying_key(public_key)?;
143    let mut r = [0u8; 32];
144    r.copy_from_slice(&sig[..32]);
145    if !is_canonical_point_encoding(&r) {
146        return Ok(false);
147    }
148    // verify_strict (not verify): refuses an R of small order and a small-order
149    // public key, and compares R byte for byte with the recomputed (canonical)
150    // R; ed25519-dalek also refuses S >= L. Honest signatures are unaffected.
151    Ok(vk
152        .verify_strict(message, &Signature::from_bytes(&sig))
153        .is_ok())
154}
155
156/// Encode an Ed25519 public key as a did:key DID.
157pub fn ed25519_to_did_key(public_key: &[u8]) -> Result<String> {
158    Ok(format!(
159        "did:key:{}",
160        multikey::encode_ed25519_public(public_key)?
161    ))
162}
163
164/// Extract the Ed25519 public key bytes from a did:key DID. The multikey must
165/// carry the Ed25519 public-key codec and a strict, non-weak 32-byte key (see
166/// [`multikey::decode`]).
167pub fn did_key_to_ed25519(did: &str) -> Result<Vec<u8>> {
168    let mk = did
169        .strip_prefix("did:key:")
170        .ok_or_else(|| CoreError::InvalidDid("not a did:key".into()))?;
171    let decoded = multikey::decode(mk)?;
172    if decoded.algorithm != "Ed25519" {
173        return Err(CoreError::InvalidDid(format!(
174            "did:key is {} not Ed25519",
175            decoded.algorithm
176        )));
177    }
178    Ok(decoded.raw_key)
179}
180
181#[cfg(test)]
182pub(crate) mod tests {
183    use super::*;
184
185    /// Every encoding of a small-order Ed25519 point (the 8 torsion points,
186    /// with sign-bit and y >= p spellings), computed with exact field
187    /// arithmetic over 2^255 - 19 (multiply points by the group order to land
188    /// in the torsion subgroup, then enumerate its spellings).
189    pub(crate) const SMALL_ORDER_ENCODINGS: [&str; 14] = [
190        "0000000000000000000000000000000000000000000000000000000000000000",
191        "0000000000000000000000000000000000000000000000000000000000000080",
192        "0100000000000000000000000000000000000000000000000000000000000000",
193        "0100000000000000000000000000000000000000000000000000000000000080",
194        "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
195        "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
196        "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
197        "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
198        "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
199        "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
200        "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
201        "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
202        "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
203        "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
204    ];
205
206    /// y = p + 3 and y = p + 18: points that are on the curve and not of small
207    /// order, spelled with y >= p. Their canonical spellings (y = 3, y = 18)
208    /// decode fine.
209    pub(crate) const NON_CANONICAL_ENCODINGS: [&str; 2] = [
210        "f0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
211        "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
212    ];
213
214    pub(crate) fn unhex32(h: &str) -> [u8; 32] {
215        let mut out = [0u8; 32];
216        for (i, b) in out.iter_mut().enumerate() {
217            *b = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).unwrap();
218        }
219        out
220    }
221
222    #[test]
223    fn small_order_public_keys_are_refused() {
224        for h in SMALL_ORDER_ENCODINGS {
225            let k = unhex32(h);
226            assert!(strict_verifying_key(&k).is_err(), "{h}");
227            // R = the same point and S = 0 is the classic "verifies for any
228            // message" signature; it must never verify.
229            let mut sig = [0u8; 64];
230            sig[..32].copy_from_slice(&k);
231            assert!(verify(&k, b"any message", &sig).is_err(), "{h}");
232        }
233    }
234
235    #[test]
236    fn non_canonical_public_keys_are_refused() {
237        for h in NON_CANONICAL_ENCODINGS {
238            let k = unhex32(h);
239            assert!(!is_canonical_point_encoding(&k));
240            // ed25519-dalek alone would accept these; the canonical check is
241            // what refuses them.
242            assert!(VerifyingKey::from_bytes(&k).is_ok(), "{h} is a curve point");
243            assert!(strict_verifying_key(&k).is_err(), "{h}");
244        }
245        let mut three = [0u8; 32];
246        three[0] = 3;
247        assert!(strict_verifying_key(&three).is_ok());
248        // The boundary: y = p - 1 is canonical, y = p is not (sign bit ignored).
249        assert!(is_canonical_point_encoding(&unhex32(
250            SMALL_ORDER_ENCODINGS[8]
251        )));
252        assert!(!is_canonical_point_encoding(&unhex32(
253            SMALL_ORDER_ENCODINGS[10]
254        )));
255        assert!(!is_canonical_point_encoding(&unhex32(
256            SMALL_ORDER_ENCODINGS[11]
257        )));
258    }
259
260    #[test]
261    fn small_order_or_non_canonical_r_is_refused() {
262        let kp = Ed25519KeyPair::from_seed(&[8u8; 32]);
263        let msg = b"vouch protocol";
264        let good = kp.sign(msg);
265        assert!(verify(&kp.public_key(), msg, &good).unwrap());
266        for h in SMALL_ORDER_ENCODINGS
267            .iter()
268            .chain(NON_CANONICAL_ENCODINGS.iter())
269        {
270            let mut sig = good;
271            sig[..32].copy_from_slice(&unhex32(h));
272            assert!(!verify(&kp.public_key(), msg, &sig).unwrap(), "R = {h}");
273        }
274        // S >= L (here S + L) is refused.
275        let l: [u8; 32] = [
276            0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9,
277            0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
278            0x00, 0x00, 0x00, 0x10,
279        ];
280        let mut sig = good;
281        let mut carry = 0u16;
282        for i in 0..32 {
283            let v = u16::from(sig[32 + i]) + u16::from(l[i]) + carry;
284            sig[32 + i] = v as u8;
285            carry = v >> 8;
286        }
287        assert!(!verify(&kp.public_key(), msg, &sig).unwrap_or(false));
288    }
289
290    #[test]
291    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
292    fn sign_verify_roundtrip() {
293        let kp = Ed25519KeyPair::generate().unwrap();
294        let msg = b"vouch protocol";
295        let sig = kp.sign(msg);
296        assert!(verify(&kp.public_key(), msg, &sig).unwrap());
297        assert!(!verify(&kp.public_key(), b"tampered", &sig).unwrap());
298    }
299
300    #[test]
301    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
302    fn did_key_roundtrip() {
303        let kp = Ed25519KeyPair::generate().unwrap();
304        let did = kp.did_key();
305        assert!(did.starts_with("did:key:z6Mk"));
306        assert_eq!(did_key_to_ed25519(&did).unwrap(), kp.public_key().to_vec());
307    }
308
309    #[test]
310    fn seed_determinism() {
311        let seed = [3u8; 32];
312        let a = Ed25519KeyPair::from_seed(&seed);
313        let b = Ed25519KeyPair::from_seed(&seed);
314        assert_eq!(a.public_key(), b.public_key());
315    }
316}