1use num_bigint::BigUint;
18use num_traits::{One, Zero};
19use rand::Rng;
20use sha1::{Digest, Sha1};
21
22use crate::error::E2eError;
23
24pub const DEFAULT_LAYER: i32 = 101;
26
27pub struct DhCacheEntry {
29 pub g: u32,
31 pub p: Vec<u8>,
33 pub version: i32,
35}
36
37pub struct DhContext {
40 pub private_key: [u8; 256],
42 pub public_value: Vec<u8>,
44 pub g: u32,
46 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
59pub 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
80pub 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 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 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
127pub 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}