Skip to main content

ferogram_crypto/
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
15use num_bigint::BigUint;
16
17/// Compute `base^exp mod modulus` over arbitrary-precision big-endian byte slices.
18///
19/// All three inputs are big-endian byte slices. Returns big-endian bytes,
20/// zero-padded to nothing (caller pads if needed).
21///
22/// Used for MTProto DH key exchange: `g^b mod p` and `g_a^b mod p`.
23pub fn dh_modpow(base: &[u8], exp: &[u8], modulus: &[u8]) -> Vec<u8> {
24    BigUint::from_bytes_be(base)
25        .modpow(
26            &BigUint::from_bytes_be(exp),
27            &BigUint::from_bytes_be(modulus),
28        )
29        .to_bytes_be()
30}