· 8 years ago · Nov 24, 2017, 10:04 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
11 Scanner ssc=new Scanner(System.in);
12 Random sc = new SecureRandom();
13 secretKey = new BigInteger("12345678901234567890");
14 //Calculating Public key
15 System.out.println("secretKey = " + secretKey);
16 p = BigInteger.probablePrime(64, sc);
17 b = new BigInteger("3");
18 c = b.modPow(secretKey, p);
19 System.out.println("p = " + p);
20 System.out.println("b = " + b);
21 System.out.println("c = " + c);
22 //Input
23 System.out.print("Enter the 3x3 image matrix to encrypt");
24
25 String s[][]= new String[3][3];
26 for(int i=0;i<3;i++)
27 {
28 for(int j=0;j<3;j++)
29 {
30 s[i][j]=ssc.nextLine();
31 }
32 }
33 for(int i=0;i<3;i++)
34 {
35 for(int j=0;j<3;j++)
36 {
37 //Encryption
38 BigInteger X = new BigInteger(s[i][j]);
39 BigInteger r = new BigInteger(64, sc);
40 BigInteger EC = X.multiply(c.modPow(r, p)).mod(p);
41 BigInteger brmodp = b.modPow(r, p);
42 System.out.println("Plaintext = " + X);
43 //System.out.println("r = " + r);
44 System.out.println("Encrypted msg = " + EC);
45 System.out.println("b^r mod p = " + brmodp);
46 //Decryption
47 BigInteger crmodp = brmodp.modPow(secretKey, p);
48 BigInteger d = crmodp.modInverse(p);
49 BigInteger dec = d.multiply(EC).mod(p);
50 System.out.println("\n\nc^r mod p = " + crmodp);
51 //System.out.println("d = " + d);
52 System.out.println("Decrypted msg " + dec);
53 }
54 System.out.println();
55 }
56
57 }
58}