export class DiffieHellman {
constructor(p, g) {
if (!this.isPrime(p) || !this.isPrime(g)) {
throw new Error('Arguments must be prime');
}
this.p = p;
this.g = g;
}
isPrime(n) {
if (n <= 1) return false;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) return false;
}
return true;
}
getPublicKey(privateKey) {
if (privateKey <= 1 || privateKey >= this.p) {
throw new Error('Invalid private key');
}
return BigInt(this.g) ** BigInt(privateKey) % BigInt(this.p);
}
getSecret(theirPublicKey, myPrivateKey) {
return BigInt(theirPublicKey) ** BigInt(myPrivateKey) % BigInt(this.p);
}
}