forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathElGamalCipher.java
More file actions
37 lines (31 loc) · 1.13 KB
/
ElGamalCipher.java
File metadata and controls
37 lines (31 loc) · 1.13 KB
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
34
35
36
37
package com.thealgorithms.ciphers;
import java.math.BigInteger;
import java.security.SecureRandom;
public class ElGamalCipher {
private BigInteger p;
private BigInteger g;
private BigInteger x;
private BigInteger y;
private SecureRandom random = new SecureRandom();
// Key generation
public void generateKeys(int bitLength) {
p = BigInteger.probablePrime(bitLength, random);
g = new BigInteger(bitLength - 1, random).mod(p);
x = new BigInteger(bitLength - 2, random); // Private key
y = g.modPow(x, p); // Public key
}
// Encryption: returns [c1, c2]
public BigInteger[] encrypt(BigInteger message) {
BigInteger k = new BigInteger(p.bitLength() - 1, random);
BigInteger c1 = g.modPow(k, p);
BigInteger s = y.modPow(k, p);
BigInteger c2 = s.multiply(message).mod(p);
return new BigInteger[] {c1, c2};
}
// Decryption: m = c2 * (c1^x)^-1 mod p
public BigInteger decrypt(BigInteger c1, BigInteger c2) {
BigInteger s = c1.modPow(x, p);
BigInteger sInv = s.modInverse(p);
return c2.multiply(sInv).mod(p);
}
}