Skip to main content

platform_encryption/
ecdh.rs

1//! DIP-15 ECDH shared-secret derivation.
2
3use secp256k1::{PublicKey, SecretKey};
4
5/// Derive a shared secret key using ECDH as specified in DIP-15
6///
7/// This uses libsecp256k1_ecdh which computes: SHA256((y[31]&0x1|0x2) || x)
8/// where (x, y) is the EC point result of scalar multiplication
9///
10/// # Arguments
11/// * `private_key` - The private key for this side of the exchange
12/// * `public_key` - The public key from the other party
13///
14/// # Returns
15/// A 32-byte shared secret key
16pub fn derive_shared_key_ecdh(private_key: &SecretKey, public_key: &PublicKey) -> [u8; 32] {
17    use secp256k1::ecdh::SharedSecret;
18
19    // Use secp256k1's built-in ECDH which matches libsecp256k1_ecdh
20    // This computes SHA256((y[31]&0x1|0x2) || x) internally
21    let shared_secret = SharedSecret::new(public_key, private_key);
22
23    let mut key = [0u8; 32];
24    key.copy_from_slice(shared_secret.as_secret_bytes());
25    key
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31    use secp256k1::generate_keypair;
32    use secp256k1::rand::rngs::StdRng;
33    use secp256k1::rand::SeedableRng;
34
35    #[test]
36    fn test_ecdh_key_derivation() {
37        let mut rng = StdRng::seed_from_u64(1);
38
39        // Generate two key pairs
40        let (secret1, public1) = generate_keypair(&mut rng);
41        let (secret2, public2) = generate_keypair(&mut rng);
42
43        // Derive shared keys from both sides
44        let shared1 = derive_shared_key_ecdh(&secret1, &public2);
45        let shared2 = derive_shared_key_ecdh(&secret2, &public1);
46
47        // Both sides should derive the same shared key
48        assert_eq!(shared1, shared2);
49    }
50
51    /// Known-answer test for the ECDH shared-key convention. We had been
52    /// trusting `SharedSecret::new` to compute `SHA256((y[31]&1|2) || x)` from
53    /// a library comment, not bytes — a cross-impl mismatch with dashj would
54    /// break contactRequest/contactInfo interop silently. This recomputes the
55    /// shared key by hand for fixed keys and pins (a) symmetry `a·B == b·A` and
56    /// (b) the exact compressed-y-prefix-‖-x preimage convention.
57    #[test]
58    fn ecdh_matches_sha256_y_parity_prefix_convention() {
59        use secp256k1::Scalar;
60        use sha2::{Digest, Sha256};
61
62        let priv_a = SecretKey::from_secret_bytes([0xC0u8; 32]).expect("valid scalar");
63        let priv_b = SecretKey::from_secret_bytes([0x0Du8; 32]).expect("valid scalar");
64        let pub_a = PublicKey::from_secret_key(&priv_a);
65        let pub_b = PublicKey::from_secret_key(&priv_b);
66
67        let ab = derive_shared_key_ecdh(&priv_a, &pub_b);
68        let ba = derive_shared_key_ecdh(&priv_b, &pub_a);
69        assert_eq!(ab, ba, "ECDH must be symmetric (a·B == b·A)");
70        assert_eq!(ab, derive_shared_key_ecdh(&priv_a, &pub_b), "deterministic");
71
72        // Recompute by hand: shared point P = a·B; shared key =
73        // SHA256( (0x02 | (P.y & 1)) ‖ P.x ). Pins that it's the compressed-y
74        // prefix + x, NOT x‖y or some other layout.
75        let scalar_a = Scalar::from_be_bytes([0xC0u8; 32]).expect("scalar in range");
76        let shared_point = pub_b.mul_tweak(&scalar_a).expect("point mul");
77        let uncompressed = shared_point.serialize_uncompressed(); // 0x04 ‖ x(32) ‖ y(32)
78        let prefix = 0x02u8 | (uncompressed[64] & 1); // y parity from the last y byte
79        let mut preimage = Vec::with_capacity(33);
80        preimage.push(prefix);
81        preimage.extend_from_slice(&uncompressed[1..33]); // x
82        let mut manual = [0u8; 32];
83        manual.copy_from_slice(&Sha256::digest(&preimage));
84        assert_eq!(ab, manual, "ECDH must be SHA256((y&1|2)‖x)");
85    }
86}