Diffie-Hellman alone does not prove who sent A and B. Mallory, sitting in the middle, replaces both with her own value and ends up sharing one key with each side.
What to build
Work out the keys Anika and Babul end up with when Mallory swaps in her own value, and show that Mallory knows both.
Requirements
- Anika sends A = g^a mod p and Babul sends B = g^b mod p, but Mallory replaces both with M = g^m mod p.
- Anika's key is M^a mod p and Babul's key is M^b mod p.
- Mallory computes A^m mod p and B^m mod p.
- Print
Anika's key x,Babul's key y, thenMallory knows both: yesif her two numbers equal x and y (they always should), andAnika and Babul share a key: yesorno.
Input
One line: p g a b m.
Output
Four lines.
Constraints
p is a prime up to 10⁹, and g, a, b and m are 1 to p − 1. Use BigInt.
Example
Input:
23 5 6 15 13
Output:
Anika's key 18
Babul's key 7
Mallory knows both: yes
Anika and Babul share a key: no
Why it works
Each side really does run a correct exchange, but with Mallory instead of each other: M^a = A^m and M^b = B^m. Signing A and B with certified keys stops the swap, because Mallory cannot sign M as Anika or as Babul.
Examples
23 5 6 15 13
Anika's key 18 Babul's key 7 Mallory knows both: yes Anika and Babul share a key: no
23 5 3 4 7
Anika's key 14 Babul's key 8 Mallory knows both: yes Anika and Babul share a key: no
Hints
Hint 1
Reuse modPow; there are only six powers to compute.
Hint 2
The two victims share a key only by coincidence, when g^(am) and g^(bm) happen to be equal modulo p.
Solution
Show one correct solution (try it yourself first)
function modPow(b, e, n) {
let result = 1n % n;
b %= n;
while (e > 0n) {
if (e & 1n) result = (result * b) % n;
b = (b * b) % n;
e >>= 1n;
}
return result;
}
const [p, g, a, b, m] = prompt().trim().split(/\s+/).map(BigInt);
const A = modPow(g, a, p), B = modPow(g, b, p), M = modPow(g, m, p);
const anika = modPow(M, a, p);
const babul = modPow(M, b, p);
console.log(`Anika's key ${anika}`);
console.log(`Babul's key ${babul}`);
console.log(`Mallory knows both: ${modPow(A, m, p) === anika && modPow(B, m, p) === babul ? "yes" : "no"}`);
console.log(`Anika and Babul share a key: ${anika === babul ? "yes" : "no"}`);
▶ Open this solution in the compiler, then press Visualize to watch it run step by step