Two people agree on a public prime p and a number g, each keeps a secret exponent, and both end up with the same key.
What to build
Given p, g and the two secrets, print the two public values and the shared key.
Requirements
- A = g^a mod p and B = g^b mod p.
- Check that both sides reach the same key: B^a mod p and A^b mod p.
- Print
A x,B yandkey kon three lines, orkeys differinstead of the key line if they do not match (they always should).
Input
One line: p g a b.
Output
Three lines.
Constraints
p is a prime up to 10⁹. g, a and b are 1 to p − 1. Use BigInt or repeated squaring that keeps products safe.
Example
Input:
23 5 6 15
Output:
A 8
B 19
key 2
Why it works
B^a = (g^b)^a = g^(ab) = (g^a)^b = A^b, all modulo p, so both sides compute the same number without either secret being sent.
Examples
Example 1 · Input
23 5 6 15
Expected output
A 8 B 19 key 2
Example 2 · Input
23 5 3 4
Expected output
A 10 B 4 key 18
Hints
Hint 1
Reuse a modular power function.
Hint 2
Products of two numbers below 10⁹ can pass 2⁵³, so BigInt is the safe choice.
Solution
Show one correct solution (try it yourself first)
function modPow(b, e, m) {
let result = 1n % m;
b %= m;
while (e > 0n) {
if (e & 1n) result = (result * b) % m;
b = (b * b) % m;
e >>= 1n;
}
return result;
}
const [p, g, a, b] = prompt().trim().split(/\s+/).map(BigInt);
const A = modPow(g, a, p);
const B = modPow(g, b, p);
console.log(`A ${A}`);
console.log(`B ${B}`);
const k1 = modPow(B, a, p);
const k2 = modPow(A, b, p);
console.log(k1 === k2 ? `key ${k1}` : "keys differ");
▶ Open this solution in the compiler, then press Visualize to watch it run step by step