· 8 years ago · Nov 24, 2017, 09:28 AM
1import java.math.*;
2import java.util.*;
3import java.security.*;
4import java.io.*;
5public class elgamel
6{
7 public static void main(String[] args) throws IOException
8 {
9 BigInteger p, b, c, secretKey;
10 Scanner ssc=new Scanner(System.in);
11 Random sc = new SecureRandom();
12 secretKey = new BigInteger("12345678901234567890");
13 //Calculating Public key
14 System.out.println("secretKey = " + secretKey);
15 p = BigInteger.probablePrime(64, sc);
16 b = new BigInteger("3");
17 c = b.modPow(secretKey, p);
18 System.out.println("p = " + p);
19 System.out.println("b = " + b);
20 System.out.println("c = " + c);
21 //Encrytping
22 System.out.print("Enter the number to encrypt");
23 String s = ssc.nextLine();
24 BigInteger X = new BigInteger(s);
25 BigInteger r = new BigInteger(64, sc);
26 BigInteger EC = X.multiply(c.modPow(r, p)).mod(p);
27 BigInteger brmodp = b.modPow(r, p);
28 System.out.println("Plaintext = " + X);
29 System.out.println("r = " + r);
30 System.out.println("EC = " + EC);
31 System.out.println("b^r mod p = " + brmodp);
32 //Decrypting
33 BigInteger crmodp = brmodp.modPow(secretKey, p);
34 BigInteger d = crmodp.modInverse(p);
35 BigInteger ad = d.multiply(EC).mod(p);
36 System.out.println("\n\nc^r mod p = " + crmodp);
37 System.out.println("d = " + d);
38 System.out.println("Decrypted msg " + ad);
39
40 }
41}