Skip to main content

ferogram_e2e/
dh.rs

1/*
2 * Copyright (c) 2026 Ankit Chaubey <ankitchaubey.dev@gmail.com>
3 * https://github.com/ankit-chaubey
4 *
5 * Project: ferogram
6 * Website: https://ferogram.dev
7 *
8 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
9 * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
10 * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
11 * This file may not be copied, modified, or distributed except according
12 * to those terms.
13 */
14
15//! Diffie-Hellman helpers for the secret chat key exchange.
16
17use num_bigint::BigUint;
18use num_traits::{One, Zero};
19use rand::Rng;
20use sha1::{Digest, Sha1};
21
22use crate::error::E2eError;
23
24/// Secret chat layer this crate advertises to the peer via `notify_layer`.
25pub const DEFAULT_LAYER: i32 = 101;
26
27/// Cached DH configuration from `messages.getDhConfig`.
28pub struct DhCacheEntry {
29    /// Generator.
30    pub g: u32,
31    /// Safe prime, big-endian.
32    pub p: Vec<u8>,
33    /// Config version, sent back to the server to detect changes.
34    pub version: i32,
35}
36
37/// Active DH state for one side of a key exchange.
38/// Holds the private exponent and the computed public value (g^private mod p).
39pub struct DhContext {
40    /// Private exponent, 256 bytes.
41    pub private_key: [u8; 256],
42    /// g^private mod p, exactly 256 bytes (left-padded with zeros if needed).
43    pub public_value: Vec<u8>,
44    /// Generator.
45    pub g: u32,
46    /// Safe prime, big-endian.
47    pub p: Vec<u8>,
48}
49
50fn to_256_bytes(n: &BigUint) -> [u8; 256] {
51    let raw = n.to_bytes_be();
52    let mut out = [0u8; 256];
53    let start = 256usize.saturating_sub(raw.len());
54    let src_start = raw.len().saturating_sub(256);
55    out[start..].copy_from_slice(&raw[src_start..]);
56    out
57}
58
59/// Validate a DH public value against the prime.
60///
61/// Applies to both `g_a` and `g_b`: the value must lie strictly between 1 and
62/// `p - 1`, and at least 2^(2048-64) away from both ends of that range.
63pub fn validate_dh_value(val: &BigUint, p: &BigUint) -> Result<(), E2eError> {
64    if val <= &BigUint::one() {
65        return Err(E2eError::DhValidationFailed);
66    }
67    if val >= &(p - BigUint::one()) {
68        return Err(E2eError::DhValidationFailed);
69    }
70    let bound = BigUint::one() << 1984u32;
71    if val < &bound {
72        return Err(E2eError::DhValidationFailed);
73    }
74    if val > &(p - &bound) {
75        return Err(E2eError::DhValidationFailed);
76    }
77    Ok(())
78}
79
80/// Compute key_fingerprint = last 8 bytes of SHA1(auth_key) as little-endian i64.
81pub fn compute_fingerprint(auth_key: &[u8; 256]) -> i64 {
82    let hash: [u8; 20] = Sha1::digest(auth_key).into();
83    let mut b = [0u8; 8];
84    b.copy_from_slice(&hash[12..20]);
85    i64::from_le_bytes(b)
86}
87
88impl DhContext {
89    /// Generate a fresh DH context: random private key, compute public value.
90    pub fn generate(g: u32, p_bytes: &[u8]) -> Result<Self, E2eError> {
91        let mut private_key = [0u8; 256];
92        rand::rng().fill_bytes(&mut private_key);
93
94        let p = BigUint::from_bytes_be(p_bytes);
95        let a = BigUint::from_bytes_be(&private_key);
96        let public = BigUint::from(g).modpow(&a, &p);
97
98        validate_dh_value(&public, &p)?;
99
100        Ok(Self {
101            private_key,
102            public_value: to_256_bytes(&public).to_vec(),
103            g,
104            p: p_bytes.to_vec(),
105        })
106    }
107
108    /// Compute shared secret: remote_public^private mod p.
109    /// Returns exactly 256 bytes (left-padded).
110    pub fn compute_shared_secret(&self, remote_public: &[u8]) -> Result<[u8; 256], E2eError> {
111        let p = BigUint::from_bytes_be(&self.p);
112        let remote = BigUint::from_bytes_be(remote_public);
113
114        validate_dh_value(&remote, &p)?;
115
116        let private = BigUint::from_bytes_be(&self.private_key);
117        let shared = remote.modpow(&private, &p);
118
119        if shared.is_zero() || shared == BigUint::one() {
120            return Err(E2eError::SharedSecretInvalid);
121        }
122
123        Ok(to_256_bytes(&shared))
124    }
125}
126
127/// Compute the shared secret from raw private key bytes and the remote public value.
128///
129/// Used when completing a chat on the initiator side (User A), where only the
130/// stored private exponent is available rather than a full [`DhContext`].
131pub fn compute_shared_from_raw(
132    private_key: &[u8; 256],
133    remote_public: &[u8],
134    p_bytes: &[u8],
135) -> Result<[u8; 256], E2eError> {
136    let p = BigUint::from_bytes_be(p_bytes);
137    let remote = BigUint::from_bytes_be(remote_public);
138
139    validate_dh_value(&remote, &p)?;
140
141    let a = BigUint::from_bytes_be(private_key);
142    let shared = remote.modpow(&a, &p);
143
144    if shared.is_zero() || shared == BigUint::one() {
145        return Err(E2eError::SharedSecretInvalid);
146    }
147
148    Ok(to_256_bytes(&shared))
149}