-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdiffie-hellman.js
More file actions
33 lines (25 loc) · 779 Bytes
/
Copy pathdiffie-hellman.js
File metadata and controls
33 lines (25 loc) · 779 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const isPrime = integer => {
if (integer < 2) return false;
for (let factor = 2; factor <= Math.floor(integer / 2); factor += 1) {
if (integer % factor === 0) return false;
}
return true;
};
const INVALID_P = new Error("Invalid p");
const INVALID_G = new Error("Invalid g");
const INVALID_PRIVATE_KEY = new Error("Invalid private key");
export class DiffieHellman {
constructor(p, g) {
if (!isPrime(p)) throw INVALID_P;
if (!isPrime(g)) throw INVALID_G;
this.p = p;
this.g = g;
}
getPublicKeyFromPrivateKey(privateKey) {
if (privateKey <= 1 || privateKey >= this.p) throw INVALID_PRIVATE_KEY;
return this.g ** privateKey % this.p;
}
getSharedSecret(privateKey, publicKey) {
return publicKey ** privateKey % this.p;
}
}