labda3
labda3
1. RSA
2. Elgammal
Code:
import java.util.Scanner;
if (p <= 1 || q <= 1 || p == q) {
System.out.println("Invalid input! Both numbers should be
distinct primes.");
return;
}
n = p * q;
phi = (p - 1) * (q - 1);
// Selecting e
for (e = 2; e < phi; e++) {
if (gcd(e, phi) == 1) {
break;
}
}
d = modInverse(e, phi);
if (d == -1) {
System.out.println("Error: Could not find modular inverse!");
return;
}
// Menu-driven approach
public static void main(String[] args) {
while (true) {
System.out.println("\n----- RSA Simulation Menu -----");
System.out.println("1. Generate RSA Keys");
System.out.println("2. Encrypt Message");
System.out.println("3. Decrypt Message");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
switch (choice) {
case 1:
generateKeys();
break;
case 2:
encryptMessage();
break;
case 3:
decryptMessage();
break;
case 4:
System.out.println("Exiting program...");
sc.close();
return;
default:
System.out.println("Invalid choice! Please select a valid
option.");
}
}
}
}
Outputs:
2. Elgammal:
Pseudocode:
Code:
import java.util.Random;
import java.util.Scanner;
// Compute decryption
long rX = modExp(rReceived, x, p); // r^x % p
long rXInverse = modExp(rX, p - 2, p); // Modular inverse using
Fermat's theorem
decryptedMessage = (cReceived * rXInverse) % p;
// Menu-driven approach
public static void main(String[] args) {
while (true) {
System.out.println("\n----- ElGamal Encryption Menu -----");
System.out.println("1. Generate Keys");
System.out.println("2. Encrypt Message");
System.out.println("3. Decrypt Message");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
switch (choice) {
case 1:
generateKeys();
break;
case 2:
encryptMessage();
break;
case 3:
decryptMessage();
break;
case 4:
System.out.println("Exiting program...");
sc.close();
return;
default:
System.out.println("Invalid choice! Please select a valid
option.");
}
}
}
}
Outputs: