-
Notifications
You must be signed in to change notification settings - Fork 0
/
rsa.cpp
64 lines (49 loc) · 1.25 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
#include <iostream>
#include <cmath>
using namespace std;
int gcd(int a, int b){
if (b == 0)
return a;
return gcd(b, a % b);
}
int modexp(int base, int exponent, int modulus){
int result = 1;
while (exponent > 0) {
if (exponent % 2 == 1)
result = (result * base) % modulus;
base = (base * base) % modulus;
exponent = exponent / 2;
}
return result;
}
void generate_keys(int p, int q, int& e, int& d, int& n){
n = p * q;
int totient = (p - 1) * (q - 1);
for (e = 2; e < totient; e++) {
if (gcd(e, totient) == 1)
break;
}
for (d = 1; d < totient; d++) {
if ((d * e) % totient == 1)
break;
}
}
int encrypt(int message, int e, int n){
return modexp(message, e, n);
}
int decrypt(int message, int d, int n){
return modexp(message, d, n);
}
int main(){
int p = 7, q = 11;
int e, d, n;
generate_keys(p, q, e, d, n);
int message;
cout << "Enter your message: ";
cin >> message;
int ciphertext = encrypt(message, e, n);
cout << "Encrypted message: " << ciphertext << endl;
int plaintext = decrypt(ciphertext, d, n);
cout << "Decrypted message: " << plaintext << endl;
return 0;
}