import java.math.BigInteger; import java.security.SecureRandom; import java.util.Scanner; public class elgamal { public static void main(String[] args) { Scanner sc = new Scanner(System.in); SecureRandom random = new SecureRandom(); BigInteger p = BigInteger.valueOf(467); BigInteger g = BigInteger.valueOf(2); BigInteger x = BigInteger.valueOf(127); BigInteger y = g.modPow(x, p); System.out.println("ElGamal Cryptosystem"); System.out.println("--------------------"); System.out.println("Prime (p) = " + p); System.out.println("Generator (g) = " + g); System.out.println("Private key (x) = " + x); System.out.println("Public key (y) = " + y); System.out.print("\nEnter message (less than p): "); BigInteger m = sc.nextBigInteger(); BigInteger k; do { k = new BigInteger(p.bitLength(), random); } while (k.compareTo(BigInteger.ONE) <= 0 || k.compareTo(p.subtract(BigInteger.ONE)) >= 0); // Encryption BigInteger c1 = g.modPow(k, p); BigInteger c2 = m.multiply(y.modPow(k, p)).mod(p); System.out.println("\nEphemeral key (k) = " + k); System.out.println("Ciphertext (c1) = " + c1); System.out.println("Ciphertext (c2) = " + c2); // Decryption BigInteger s = c1.modPow(x, p); BigInteger decrypted = c2.multiply(s.modInverse(p)).mod(p); System.out.println("\nOriginal Message = " + m); System.out.println("Decrypted Message = " + decrypted); sc.close(); } }