· 6 years ago · Apr 03, 2019, 07:34 PM
1Practical No.5: Write a program to implement the ElGamal Cryptosystem to generate keys and perform encryption and decryption.
2
3Source Code:
4package cryptanalysis;
5import java.math.*;
6import java.util.*;
7import java.security.*;
8import java.io.*;
9
10public class ElGamal
11{
12 public static void main(String[] args) throws IOException
13 {
14 BigInteger p, b, c, secretKey;
15 Random sc = new SecureRandom();
16 secretKey = new BigInteger("12345678901234567890");
17 // public key calculation
18 System.out.println("secretKey = " + secretKey);
19 p = BigInteger.probablePrime(64, sc);
20 b = new BigInteger("3");
21 c = b.modPow(secretKey, p);
22 System.out.println("p = " + p);
23 System.out.println("b = " + b);
24 System.out.println("c = " + c);
25 // Encryption
26 System.out.print("Enter your Big Number message -->");
27 Scanner sca=new Scanner(System.in);
28 String s = sca.nextLine();
29 BigInteger X = new BigInteger(s);
30 BigInteger r = new BigInteger(64, sc);
31 BigInteger EC = X.multiply(c.modPow(r, p)).mod(p);
32 BigInteger brmodp = b.modPow(r, p);
33 System.out.println("Plaintext = " + X);
34 System.out.println("r = " + r);
35 System.out.println("EC = " + EC);
36 System.out.println("b^r mod p = " + brmodp);
37 // Decryption
38 BigInteger crmodp = brmodp.modPow(secretKey, p);
39 BigInteger d = crmodp.modInverse(p);
40 BigInteger ad = d.multiply(EC).mod(p);
41 System.out.println("\n\nc^r mod p = " + crmodp);
42 System.out.println("d = " + d);
43 System.out.println("Alice decodes: " + ad);
44 }
45}