-
Notifications
You must be signed in to change notification settings - Fork 2
/
RSA.cpp
155 lines (122 loc) · 2.88 KB
/
RSA.cpp
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#include<bits/stdc++.h>
using namespace std;
int modular(int base, unsigned int exp, unsigned int mod)
{
int x = 1;
int i;
int power = base % mod;
for (i = 0; i < sizeof(int) * 8; i++) {
int least_sig_bit = 0x00000001 & (exp >> i);
if (least_sig_bit)
x = (x * power) % mod;
power = (power * power) % mod;
}
return x;
}
int modInverse(int a, int m)
{
int m0 = m;
int y = 0, x = 1;
if (m == 1)
return 0;
while (a > 1)
{
int q = a / m;
int t = m;
m = a % m, a = t;
t = y;
y = x - q * y;
x = t;
}
if (x < 0)
x += m0;
return x;
}
int gcd(int a, int b)
{
if (a == 0 || b == 0)
return 0;
if (a == b)
return a;
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
int lcm(int a, int b)
{
return (a*b)/gcd(a, b);
}
int isPrime(int n){
int flag = 1;
for(int i=2;i<=sqrt(n);i++)
{
if(n%i==0)
{
flag = 0;
return flag;
}
}
return flag;
}
int main(){
int message;
char m;
cout<<"enter the message to be encrypted: ";
cin>>m;
message = (int)m;
cout<<"The corresponding ASCII value: "<<message<<endl;
int p,q;
int random;
srand (time(NULL));
int i=0;
int a[2];
generate:
while(i<2){
random = rand() % 40 + 3;
if(isPrime(random)){
a[i]=random;
i++;
}
}
i=0;
p=a[0];
q=a[1];
if(p==q){
goto generate;
}
cout<<"The two random prime numbers are: "<<p<<" and "<<q<<endl;
int n;
n = p*q;
int phi = (p-1)*(q-1);
int lambda = lcm(p-1,q-1);
int e;
vector<int> tot;
for(int i=3;i<lambda;i++)
{
if(gcd(i,lambda) == 1){
tot.push_back(i);
}
}
int size = tot.size();
int ran = rand() % size;
e = tot[ran];
cout<<"The modulus is: "<<n<<endl;
cout<<"The phi(n) is: "<<phi<<endl;
cout<<"The lambda(n) is:"<<lambda<<endl;
cout<<"The toitient is: "<<e<<endl;
cout<<"The public key is: ("<<n<<","<<e<<")"<<endl;
long long int encrypt;
encrypt = modular(message,e,n);
cout<<"The Encrypted text is: "<<(char)encrypt<<endl;
cout<<"The Encrypted text in ASCII value is: "<<encrypt<<endl;
long long int d = modInverse(e,lambda);
if(d==e){
cout<<endl<<endl<<"aborting......"<<endl<<endl<<"Restarting the process"<<endl<<endl;
goto generate;
}
cout<<"The private key is: "<<d<<endl;
long long int decrypted;
decrypted = modular(encrypt,d,n);
cout<<"The Decrypted text is : "<<(char)decrypted<<endl;
cout<<"The Decrypted text in ASCII value is: "<<decrypted<<endl;
return 0;}