torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
//! Diffie–Hellman for MSE (768-bit MODP group).

use num_bigint::BigUint;
use num_traits::{One, Zero};

use crate::error::{Error, Result};

/// Vuze / MSE 768-bit prime P (96 bytes).
const P_HEX: &str = concat!(
    "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1",
    "29024E088A67CC74020BBEA63B139B22514A08798E3404DD",
    "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245",
    "E485B576625E7EC6F44C42E9A63A36210000000000090563"
);

pub const PUBLIC_KEY_LEN: usize = 96;
const PRIVATE_KEY_BYTES: usize = 20; // 160-bit recommended

pub struct DhKeyPair {
    pub secret: BigUint,
    pub public: BigUint,
}

pub fn prime() -> BigUint {
    BigUint::parse_bytes(P_HEX.as_bytes(), 16).expect("MSE P")
}

pub fn generate_keypair() -> Result<DhKeyPair> {
    let p = prime();
    let mut raw = [0u8; PRIVATE_KEY_BYTES];
    getrandom::fill(&mut raw).map_err(|err| Error::Secure(format!("MSE DH CSPRNG: {err}")))?;
    // Ensure non-zero secret in range (1, p-1).
    let mut secret = BigUint::from_bytes_be(&raw);
    if secret.is_zero() {
        secret = BigUint::one();
    }
    secret %= &p;
    if secret.is_zero() {
        secret = BigUint::one();
    }
    let public = BigUint::from(2u32).modpow(&secret, &p);
    Ok(DhKeyPair { secret, public })
}

pub fn shared_secret(peer_public: &BigUint, secret: &BigUint) -> BigUint {
    peer_public.modpow(secret, &prime())
}

pub fn encode_public(y: &BigUint) -> [u8; PUBLIC_KEY_LEN] {
    let bytes = y.to_bytes_be();
    let mut out = [0u8; PUBLIC_KEY_LEN];
    if bytes.len() > PUBLIC_KEY_LEN {
        // Mod P guarantees ≤ 96 bytes; truncate defensive.
        out.copy_from_slice(&bytes[bytes.len() - PUBLIC_KEY_LEN..]);
    } else {
        out[PUBLIC_KEY_LEN - bytes.len()..].copy_from_slice(&bytes);
    }
    out
}

pub fn decode_public(bytes: &[u8; PUBLIC_KEY_LEN]) -> BigUint {
    BigUint::from_bytes_be(bytes)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dh_shared_secret_matches() {
        let a = generate_keypair().expect("a");
        let b = generate_keypair().expect("b");
        let sa = shared_secret(&b.public, &a.secret);
        let sb = shared_secret(&a.public, &b.secret);
        assert_eq!(sa, sb);
        assert_eq!(encode_public(&sa).len(), PUBLIC_KEY_LEN);
    }
}