Skip to content

Commit 61db75a

Browse files
committed
Add ElGamalCipher implementing ElGamal encryption and decryption algorithm
1 parent a008cc2 commit 61db75a

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.thealgorithms.ciphers;
2+
3+
import java.math.BigInteger;
4+
import java.security.SecureRandom;
5+
6+
public class ElGamalCipher {
7+
private BigInteger p, g, x, y;
8+
private SecureRandom random = new SecureRandom();
9+
10+
// Key generation
11+
public void generateKeys(int bitLength) {
12+
p = BigInteger.probablePrime(bitLength, random);
13+
g = new BigInteger(bitLength - 1, random).mod(p);
14+
x = new BigInteger(bitLength - 2, random); // Private key
15+
y = g.modPow(x, p); // Public key
16+
}
17+
18+
// Encryption: returns [c1, c2]
19+
public BigInteger[] encrypt(BigInteger message) {
20+
BigInteger k = new BigInteger(p.bitLength() - 1, random);
21+
BigInteger c1 = g.modPow(k, p);
22+
BigInteger s = y.modPow(k, p);
23+
BigInteger c2 = s.multiply(message).mod(p);
24+
return new BigInteger[]{c1, c2};
25+
}
26+
27+
// Decryption: m = c2 * (c1^x)^-1 mod p
28+
public BigInteger decrypt(BigInteger c1, BigInteger c2) {
29+
BigInteger s = c1.modPow(x, p);
30+
BigInteger sInv = s.modInverse(p);
31+
return c2.multiply(sInv).mod(p);
32+
}
33+
34+
// Example usage
35+
public static void main(String[] args) {
36+
ElGamalCipher elgamal = new ElGamalCipher();
37+
elgamal.generateKeys(256);
38+
39+
BigInteger message = new BigInteger("12345");
40+
BigInteger[] cipher = elgamal.encrypt(message);
41+
BigInteger decrypted = elgamal.decrypt(cipher[0], cipher[1]);
42+
43+
System.out.println("Original: " + message);
44+
System.out.println("Encrypted: c1=" + cipher[0] + ", c2=" + cipher[1]);
45+
System.out.println("Decrypted: " + decrypted);
46+
}
47+
}

0 commit comments

Comments
 (0)