Rsa
import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
static long p, q, n, phi, e, d;
// Function to compute GCD
static long gcd(long a, long b) {
while (b != 0) {
long temp = b;
b = a % b;
a = temp;
}
return a;
}
// Function to compute modular inverse
static long modInverse(long e, long phi) {
for (long d = 1; d < phi; d++) {
if ((e * d) % phi == 1) {
return d;
}
}
return -1;
}
// Function for modular exponentiation
static long modExp(long base, long exponent, long mod) {
long result = 1;
while (exponent > 0) {
if (exponent % 2 == 1) {
result = (result * base) % mod;
}
exponent /= 2;
base = (base * base) % mod;
}
return result;
}
// Function to generate RSA keys
static void generateKeys() {
System.out.print("Enter two prime numbers (p and q): ");
p = sc.nextLong();
q = sc.nextLong();
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;
}
System.out.println("Public Key: (" + e + ", " + n + ")");
System.out.println("Private Key: (" + d + ", " + n + ")");
}
// Function to encrypt a message
static void encryptMessage() {
if (n == 0) {
System.out.println("Error: Generate keys first!");
return;
}
System.out.print("Enter an integer message to encrypt: ");
long message = sc.nextLong();
if (message <= 0 || message >= n) {
System.out.println("Invalid message! It should be between 1 and
" + (n - 1));
return;
}
long cipher = modExp(message, e, n);
System.out.println("Encrypted Message: " + cipher);
}
// Function to decrypt a message
static void decryptMessage() {
if (n == 0) {
System.out.println("Error: Generate keys first!");
return;
}
System.out.print("Enter the encrypted message: ");
long cipher = sc.nextLong();
long decrypted = modExp(cipher, d, n);
System.out.println("Decrypted Message: " + decrypted);
}
// 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: ");
int choice = sc.nextInt();
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.");
}
}
}
}