Security
Diffie-Hellman from Scratch: Big Integers, Safe Primes and SHAKE128
A 512-bit Diffie-Hellman key exchange in C++ with no bignum library: my own big-integer arithmetic, Miller-Rabin testing and safe-prime generation, seeded from SHAKE128.
At a glance
- 512-bit safe prime and key exchange
- ~43 s
- 99% of it is the prime search; 64-bit takes ~0.75 s
- lines of C++
- ~1,860
- big integers, modular arithmetic, primality, key exchange
- test groups passing
- 24
- arithmetic, randomness, primes and the full exchange
Engineering write-up
The key exchange itself took about a tenth of a second. Finding the 512-bit safe prime it runs on took almost 43 seconds. Writing every big-number operation by hand makes it very clear where the work in Diffie-Hellman actually goes.
TL;DR#
A solo lab for Introduction to Cryptography at HCMUS: Diffie-Hellman key exchange in about 1,860 lines of C++14, with no big-number library. I wrote the 512-bit integer type, modular arithmetic, a SHAKE128-based random source, Miller-Rabin primality testing and safe-prime generation. Both parties derive the same shared secret, and all 24 test groups pass.
The problem#
Diffie-Hellman is two lines of math: pick a prime p and generator g, then exchange g^a mod p and g^b mod p. Making those two lines run on 512-bit numbers means building everything underneath: addition with carries, reduction, exponentiation, randomness and primality, all correct at every bit.
Key decisions#
Fixed-size integers. BigUInt is 16 limbs of 32 bits (512 bits), or 32 limbs with a build flag. A fixed size keeps the code simple, but it means no operation may ever need a 513-bit intermediate.
Reduce without overflowing. Modular reduction is binary long division where the divisor is shifted left to line up with the number and then walked back down, so the remainder never has to be doubled. Modular addition checks a >= p - b and returns a - (p - b) instead of computing a + b first.
Uniform randomness. Random numbers come from SHAKE128. To draw a number below a bound, the code takes just enough random bits and retries until the candidate is below the bound. Taking a value modulo the bound would be faster, but it would make small numbers slightly more likely.
Safe primes, so the generator check is cheap. With p = 2q + 1 and q prime, the only subgroups have order 1, 2, q or 2q. So a candidate g is usable if g² ≠ 1 and g^q ≠ 1 (mod p), two exponentiations instead of a factorisation.
The core loop#
Exponentiation is right-to-left square-and-multiply, built on mul_mod:
BigUInt result{1};
BigUInt base = mod(x, modulus);
const std::size_t n = y.bit_length();
for (std::size_t i = 0; i < n; ++i)
{
if (y.get_bit(i))
result = mul_mod(result, base, modulus);
base = mul_mod(base, base, modulus);
}
return result;It has a flaw I'll own: on the last iteration it squares base one more time, and that result is never used. The answer is still correct; the work is wasted.
Where the time goes#
| Step (512-bit run) | Time |
|---|---|
| Safe-prime search | 42.7 s (99% of the total) |
| Generator search | 0.14 s |
| Key exchange | 0.14 s |
The search draws a random q, filters it by small primes, runs 40 rounds of Miller-Rabin on q and then on p = 2q + 1. Most candidates fail, and every test is a chain of modular exponentiations. Smaller sizes show how fast this grows: about 0.75 s at 64 bits and 4 s at 128 bits on my machine, with high variance because the search is random.
The bottleneck is mul_mod, which multiplies by repeated modular addition.
Limits and what I'd do next#
- Faster multiplication. Montgomery or Barrett reduction would replace the add-and-double loop in
mul_mod. - Not constant-time. Running time depends on secret bits, so this leaks timing information. It is teaching code.
- Not a protocol. There is no authentication (so a man-in-the-middle works), no key derivation function and no validation of the other party's public key. 512-bit groups are also too small for real use.