Skip to main content

qualia_core_db/crypto/network/
x25519.rs

1//! X25519 adapter. Rejects the all-zero shared secret.
2
3use x25519_dalek::{PublicKey, StaticSecret};
4use zeroize::Zeroize;
5
6use super::errors::CryptoError;
7
8pub struct X25519Secret([u8; 32]);
9
10impl X25519Secret {
11    /// Wraps a raw X25519 secret.
12    pub fn from_bytes(bytes: [u8; 32]) -> Self {
13        Self(bytes)
14    }
15
16    fn secret(&self) -> StaticSecret {
17        StaticSecret::from(self.0)
18    }
19
20    /// Derives the public key.
21    pub fn public(&self) -> [u8; 32] {
22        PublicKey::from(&self.secret()).to_bytes()
23    }
24
25    /// X25519 DH with `peer`; fails closed on low-order point.
26    pub fn diffie_hellman(&self, peer: &[u8; 32]) -> Result<[u8; 32], CryptoError> {
27        let peer = PublicKey::from(*peer);
28        let shared = self.secret().diffie_hellman(&peer);
29        let bytes = shared.to_bytes();
30        if bytes.iter().all(|&b| b == 0) {
31            return Err(CryptoError::CryptoFailure);
32        }
33        Ok(bytes)
34    }
35}
36
37impl Drop for X25519Secret {
38    fn drop(&mut self) {
39        self.0.zeroize();
40    }
41}
42
43/// Derives the public key from `secret` without holding a lease.
44pub fn public_from_secret(secret: &[u8; 32]) -> [u8; 32] {
45    X25519Secret::from_bytes(*secret).public()
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51
52    #[test]
53    fn agreement_is_symmetric() {
54        let a = X25519Secret::from_bytes([1u8; 32]);
55        let b = X25519Secret::from_bytes([2u8; 32]);
56        let sa = a.diffie_hellman(&b.public()).unwrap();
57        let sb = b.diffie_hellman(&a.public()).unwrap();
58        assert_eq!(sa, sb);
59    }
60}