use num_bigint::BigUint;
use num_traits::{One, Zero};
use rand::Rng;
use sha1::{Digest, Sha1};
use crate::error::E2eError;
pub const DEFAULT_LAYER: i32 = 101;
pub struct DhCacheEntry {
pub g: u32,
pub p: Vec<u8>,
pub version: i32,
}
pub struct DhContext {
pub private_key: [u8; 256],
pub public_value: Vec<u8>,
pub g: u32,
pub p: Vec<u8>,
}
fn to_256_bytes(n: &BigUint) -> [u8; 256] {
let raw = n.to_bytes_be();
let mut out = [0u8; 256];
let start = 256usize.saturating_sub(raw.len());
let src_start = raw.len().saturating_sub(256);
out[start..].copy_from_slice(&raw[src_start..]);
out
}
pub fn validate_dh_value(val: &BigUint, p: &BigUint) -> Result<(), E2eError> {
if val <= &BigUint::one() {
return Err(E2eError::DhValidationFailed);
}
if val >= &(p - BigUint::one()) {
return Err(E2eError::DhValidationFailed);
}
let bound = BigUint::one() << 1984u32;
if val < &bound {
return Err(E2eError::DhValidationFailed);
}
if val > &(p - &bound) {
return Err(E2eError::DhValidationFailed);
}
Ok(())
}
pub fn compute_fingerprint(auth_key: &[u8; 256]) -> i64 {
let hash: [u8; 20] = Sha1::digest(auth_key).into();
let mut b = [0u8; 8];
b.copy_from_slice(&hash[12..20]);
i64::from_le_bytes(b)
}
impl DhContext {
pub fn generate(g: u32, p_bytes: &[u8]) -> Result<Self, E2eError> {
let mut private_key = [0u8; 256];
rand::rng().fill_bytes(&mut private_key);
let p = BigUint::from_bytes_be(p_bytes);
let a = BigUint::from_bytes_be(&private_key);
let public = BigUint::from(g).modpow(&a, &p);
validate_dh_value(&public, &p)?;
Ok(Self {
private_key,
public_value: to_256_bytes(&public).to_vec(),
g,
p: p_bytes.to_vec(),
})
}
pub fn compute_shared_secret(&self, remote_public: &[u8]) -> Result<[u8; 256], E2eError> {
let p = BigUint::from_bytes_be(&self.p);
let remote = BigUint::from_bytes_be(remote_public);
validate_dh_value(&remote, &p)?;
let private = BigUint::from_bytes_be(&self.private_key);
let shared = remote.modpow(&private, &p);
if shared.is_zero() || shared == BigUint::one() {
return Err(E2eError::SharedSecretInvalid);
}
Ok(to_256_bytes(&shared))
}
}
pub fn compute_shared_from_raw(
private_key: &[u8; 256],
remote_public: &[u8],
p_bytes: &[u8],
) -> Result<[u8; 256], E2eError> {
let p = BigUint::from_bytes_be(p_bytes);
let remote = BigUint::from_bytes_be(remote_public);
validate_dh_value(&remote, &p)?;
let a = BigUint::from_bytes_be(private_key);
let shared = remote.modpow(&a, &p);
if shared.is_zero() || shared == BigUint::one() {
return Err(E2eError::SharedSecretInvalid);
}
Ok(to_256_bytes(&shared))
}