1#[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
20pub struct Ed25519KeyPair {
22 signing: SigningKey,
23}
24
25impl Ed25519KeyPair {
26 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 pub fn from_seed(seed: &[u8; ED25519_SEED_LEN]) -> Self {
38 Self {
39 signing: SigningKey::from_bytes(seed),
40 }
41 }
42
43 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 pub fn seed(&self) -> [u8; ED25519_SEED_LEN] {
55 self.signing.to_bytes()
56 }
57
58 pub fn public_key(&self) -> [u8; ED25519_PUBLIC_LEN] {
60 self.signing.verifying_key().to_bytes()
61 }
62
63 pub fn sign(&self, message: &[u8]) -> [u8; ED25519_SIGNATURE_LEN] {
65 self.signing.sign(message).to_bytes()
66 }
67
68 pub fn public_multikey(&self) -> String {
70 multikey::encode_ed25519_public(&self.public_key()).expect("public key is always 32 bytes")
71 }
72
73 pub fn did_key(&self) -> String {
75 ed25519_to_did_key(&self.public_key()).expect("public key is always 32 bytes")
76 }
77}
78
79const 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
86pub fn is_canonical_point_encoding(encoded: &[u8; 32]) -> bool {
90 let mut y = *encoded;
91 y[31] &= 0x7f; 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 }
100
101pub 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
129pub 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 Ok(vk
152 .verify_strict(message, &Signature::from_bytes(&sig))
153 .is_ok())
154}
155
156pub 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
164pub 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 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 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 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 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 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 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}