1// Aim: Program to perform RC4 encryption with Diffie-Hellman key exchange (RC4 with Diffie-Hellman Key Exchange).
2import javax.crypto.*;
3import javax.crypto.spec.SecretKeySpec;
4import java.util.*;
5import java.math.BigInteger;
6
7public class rc4_with_diffie {
8 public static void main(String[] args) throws Exception {
9 // Diffie-Hellman Key Exchange
10 Scanner sc = new Scanner(System.in);
11 System.out.print("Enter a prime number (q): ");
12 BigInteger q = sc.nextBigInteger();
13 System.out.print("Enter a primitive root: ");
14 BigInteger a = sc.nextBigInteger();
15 System.out.print("Enter private key for user A: ");
16 BigInteger xA = sc.nextBigInteger();
17 System.out.print("Enter private key for user B: ");
18 BigInteger xB = sc.nextBigInteger();
19 BigInteger yA = a.modPow(xA, q);
20 BigInteger yB = a.modPow(xB, q);
21 BigInteger kA = yB.modPow(xA, q); // Secret key
22 BigInteger kB = yA.modPow(xB, q); // Secret key verification
23
24 if (!kA.equals(kB)) {
25 System.out.println("Error: Keys do not match!");
26 return;
27 }
28
29 System.out.println("Shared Secret Key: " + kA);
30 byte[] keyBytes = Arrays.copyOf(kA.toByteArray(), 16); // Using 16 bytes for RC4 key
31 SecretKey key = new SecretKeySpec(keyBytes, "RC4");
32
33 // RC4 Encryption and Decryption
34 System.out.print("Enter text: ");
35 sc.nextLine(); // Consume the newline
36 String msg = sc.nextLine();
37 sc.close();
38
39 Cipher cpr = Cipher.getInstance("RC4");
40 cpr.init(Cipher.ENCRYPT_MODE, key);
41 byte[] encrypted = cpr.doFinal(msg.getBytes("UTF-8"));
42 String enctext = Base64.getEncoder().encodeToString(encrypted);
43
44 cpr.init(Cipher.DECRYPT_MODE, key);
45 byte[] decrypted = cpr.doFinal(Base64.getDecoder().decode(enctext));
46 String dectext = new String(decrypted, "UTF-8");
47
48 System.out.println("Original: " + msg);
49 System.out.println("Encrypted: " + enctext);
50 System.out.println("Decrypted: " + dectext);
51 }
52}