qualia_core_db/crypto/network/
ed25519.rs1use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
4
5use super::errors::CryptoError;
6use super::types::{ED25519_PK_LEN, ED25519_SIG_LEN};
7
8const CONTEXT_V1: &[u8] = b"QDNF-ED25519-CTX-V1";
9
10pub fn sign_with_context(
12 seed: &[u8; 32],
13 message: &[u8],
14 context: &[u8],
15 sig_out: &mut [u8; ED25519_SIG_LEN],
16) -> Result<(), CryptoError> {
17 let key = SigningKey::from_bytes(seed);
18 let mut bound = [0u8; 512];
19 let n = bind_context(CONTEXT_V1, context, message, &mut bound)?;
20 let sig = key.sign(&bound[..n]);
21 sig_out.copy_from_slice(&sig.to_bytes());
22 Ok(())
23}
24
25pub fn verify_with_context(
27 public: &[u8; ED25519_PK_LEN],
28 message: &[u8],
29 context: &[u8],
30 signature: &[u8; ED25519_SIG_LEN],
31) -> Result<(), CryptoError> {
32 let key = VerifyingKey::from_bytes(public).map_err(|_| CryptoError::CryptoFailure)?;
33 let mut bound = [0u8; 512];
34 let n = bind_context(CONTEXT_V1, context, message, &mut bound)?;
35 let sig = Signature::from_bytes(signature);
36 key.verify(&bound[..n], &sig)
37 .map_err(|_| CryptoError::Unauthorized)
38}
39
40pub fn public_from_seed(seed: &[u8; 32]) -> [u8; 32] {
42 SigningKey::from_bytes(seed).verifying_key().to_bytes()
43}
44
45fn bind_context(
46 label: &[u8],
47 context: &[u8],
48 message: &[u8],
49 out: &mut [u8],
50) -> Result<usize, CryptoError> {
51 let need = 2 + label.len() + 4 + context.len() + 4 + message.len();
52 if out.len() < need {
53 return Err(CryptoError::Capacity);
54 }
55 let mut i = 0;
56 let label_len: u16 = label.len().try_into().map_err(|_| CryptoError::Range)?;
57 out[i..i + 2].copy_from_slice(&label_len.to_be_bytes());
58 i += 2;
59 out[i..i + label.len()].copy_from_slice(label);
60 i += label.len();
61 let ctx_len: u32 = context.len().try_into().map_err(|_| CryptoError::Range)?;
62 out[i..i + 4].copy_from_slice(&ctx_len.to_be_bytes());
63 i += 4;
64 out[i..i + context.len()].copy_from_slice(context);
65 i += context.len();
66 let msg_len: u32 = message.len().try_into().map_err(|_| CryptoError::Range)?;
67 out[i..i + 4].copy_from_slice(&msg_len.to_be_bytes());
68 i += 4;
69 out[i..i + message.len()].copy_from_slice(message);
70 i += message.len();
71 Ok(i)
72}
73
74#[cfg(test)]
75mod tests {
76 use super::*;
77
78 #[test]
79 fn context_mismatch_fails() {
80 let seed = [3u8; 32];
81 let pk = public_from_seed(&seed);
82 let mut sig = [0u8; 64];
83 sign_with_context(&seed, b"msg", b"ctx-a", &mut sig).unwrap();
84 assert!(verify_with_context(&pk, b"msg", b"ctx-a", &sig).is_ok());
85 assert_eq!(
86 verify_with_context(&pk, b"msg", b"ctx-b", &sig),
87 Err(CryptoError::Unauthorized)
88 );
89 }
90}