|
| 1 | +package com.thealgorithms.cryptography; |
| 2 | + |
| 3 | +import java.math.BigInteger; |
| 4 | +import java.security.SecureRandom; |
| 5 | + |
| 6 | +/** |
| 7 | + * Implementation of the ElGamal Encryption Algorithm. |
| 8 | + * |
| 9 | + * <p>This algorithm is based on the Diffie–Hellman key exchange and uses modular arithmetic |
| 10 | + * for secure public-key encryption and decryption. |
| 11 | + * |
| 12 | + * <p>Reference: |
| 13 | + * https://www.geeksforgeeks.org/elgamal-encryption-algorithm/ |
| 14 | + */ |
| 15 | +public class ElGamalEncryption { |
| 16 | + |
| 17 | + private static final SecureRandom random = new SecureRandom(); |
| 18 | + |
| 19 | + /** |
| 20 | + * Encrypts and decrypts a given message using ElGamal encryption. |
| 21 | + * |
| 22 | + * @param message The message to encrypt. |
| 23 | + * @param bitLength The bit length of the prime modulus. |
| 24 | + */ |
| 25 | + public static void runElGamal(String message, int bitLength) { |
| 26 | + BigInteger p = BigInteger.probablePrime(bitLength, random); // large prime |
| 27 | + BigInteger g = new BigInteger("2"); // primitive root |
| 28 | + BigInteger x = new BigInteger(bitLength - 2, random); // private key |
| 29 | + BigInteger y = g.modPow(x, p); // public key |
| 30 | + |
| 31 | + // Encryption |
| 32 | + BigInteger k = new BigInteger(bitLength - 2, random); |
| 33 | + BigInteger a = g.modPow(k, p); |
| 34 | + BigInteger M = new BigInteger(message.getBytes()); |
| 35 | + BigInteger b = (y.modPow(k, p).multiply(M)).mod(p); |
| 36 | + |
| 37 | + // Decryption |
| 38 | + BigInteger aInverse = a.modPow(p.subtract(BigInteger.ONE).subtract(x), p); |
| 39 | + BigInteger decrypted = (b.multiply(aInverse)).mod(p); |
| 40 | + |
| 41 | + System.out.println("Prime (p): " + p); |
| 42 | + System.out.println("Public Key (y): " + y); |
| 43 | + System.out.println("Ciphertext: (" + a + ", " + b + ")"); |
| 44 | + System.out.println("Decrypted Message: " + new String(decrypted.toByteArray())); |
| 45 | + } |
| 46 | +} |
0 commit comments