-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRSA_project.java
More file actions
102 lines (94 loc) · 3.11 KB
/
RSA_project.java
File metadata and controls
102 lines (94 loc) · 3.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import java.util.Scanner;
public class RSA_project {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Two distinct upper limits for p , q:");
System.out.print("Upper limit for p:");
int p = input.nextInt();
System.out.print("Upper limit for q:");
int q = input.nextInt();
while (!IsPrime(p)) {
p--;
}
while (!IsPrime(q)) {
q--;
}
int n = p*q;
int m = (p-1)*(q-1);
int e = 2;
while (Gcd(m, e)!=1) {
e++;
}
int d = find_d(m, e);
System.out.print("which operation to perform:\t\t");
System.out.print("1->(Encryption) || 2->(Decryption):");
int op = input.nextInt();
String cipher;
switch (op){
case 1:
System.out.print("Enter Original Message: ");
input.nextLine();
String message = input.nextLine();
cipher = Encryption(message, e, n);
System.out.println("Cipher Code: " + cipher);
break;
case 2:
System.out.print("Enter Cipher Code: ");
input.nextLine();
cipher = input.nextLine();
String decryptedMessage = Decryption(cipher, d, n);
System.out.println("Decrypted Message: " + decryptedMessage);
break;
}
input.close();
}
static boolean IsPrime(int prime) {
if (prime < 2) {
return false;
}
for (int i = 2; i < Math.sqrt(prime); i++) {
if (prime%i==0) return false;
}
return true;
}
static int Gcd(int a, int b) {
if (b == 0) return a;
return Gcd(b, a % b);
}
static int find_d(int m, int e) {
int k = 1;
while (((k*m+1.0)/e)!=(k*m+1)/e) k++;
return (k*m+1)/e;
}
static String Encryption(String message, long e, long n) {
StringBuilder cipher = new StringBuilder();
for (char ch : message.toCharArray()) {
long m = (long) ch;
long c = modularExponentiation(m, e, n);
cipher.append(c).append(" ");
}
return cipher.toString().trim();
}
static String Decryption(String cipher, long d, long n) {
StringBuilder plainText = new StringBuilder();
String[] cipherValues = cipher.split(" ");
for (String value : cipherValues) {
long c = Long.parseLong(value);
long m = modularExponentiation(c, d, n);
plainText.append((char) m);
}
return plainText.toString();
}
static long modularExponentiation(long base, long exp, long mod) {
long result = 1;
base = base % mod;
while (exp > 0) {
if (exp%2 == 1) {
result = result*base % mod;
}
exp/=2;
base = base*base % mod;
}
return result;
}
}