diff options
Diffstat (limited to 'q8/rsa.cpp')
-rw-r--r-- | q8/rsa.cpp | 81 |
1 files changed, 81 insertions, 0 deletions
diff --git a/q8/rsa.cpp b/q8/rsa.cpp new file mode 100644 index 0000000..c38e7d6 --- /dev/null +++ b/q8/rsa.cpp | |||
@@ -0,0 +1,81 @@ | |||
1 | #include <iostream> | ||
2 | #include <math.h> | ||
3 | #include <stdlib.h> | ||
4 | #include <string.h> | ||
5 | |||
6 | using namespace std; | ||
7 | |||
8 | long int gcd(long int a, long int b) { | ||
9 | if (a == 0) | ||
10 | return b; | ||
11 | if (b == 0) | ||
12 | return a; | ||
13 | return gcd(b, a % b); | ||
14 | } | ||
15 | |||
16 | long int isprime(long int a) { | ||
17 | int i; | ||
18 | for (i = 2; i < a; i++) { | ||
19 | if ((a % i) == 0) | ||
20 | return 0; | ||
21 | } | ||
22 | return 1; | ||
23 | } | ||
24 | |||
25 | long int encrypt(char ch, long int n, long int e) { | ||
26 | int i; | ||
27 | long int temp = ch; | ||
28 | for (i = 1; i < e; i++) | ||
29 | temp = (temp * ch) % n; | ||
30 | return temp; | ||
31 | } | ||
32 | |||
33 | char decrypt(long int ch, long int n, long int d) { | ||
34 | int i; | ||
35 | long int temp = ch; | ||
36 | for (i = 1; i < d; i++) | ||
37 | ch = (temp * ch) % n; | ||
38 | return ch; | ||
39 | } | ||
40 | |||
41 | int main() { | ||
42 | long int i, len; | ||
43 | long int p, q, n, phi, e, d, cipher[50]; | ||
44 | char text[50]; | ||
45 | |||
46 | cout << "Enter the text to be encrypted: "; | ||
47 | cin.getline(text, sizeof(text)); | ||
48 | len = strlen(text); | ||
49 | do { | ||
50 | p = rand() % 30; | ||
51 | } while (!isprime(p)); | ||
52 | do { | ||
53 | q = rand() % 30; | ||
54 | } while (!isprime(q)); | ||
55 | n = p * q; | ||
56 | phi = (p - 1) * (q - 1); | ||
57 | do { | ||
58 | e = rand() % phi; | ||
59 | } while (gcd(phi, e) != 1); | ||
60 | do { | ||
61 | d = rand() % phi; | ||
62 | } while (((d * e) % phi) != 1); | ||
63 | cout << "Two prime numbers (p and q) are: " << p << " and " << q << endl; | ||
64 | cout << "n(p * q) = " << p << " * " << q << " = " << p * q << endl; | ||
65 | cout << "(p - 1) * (q - 1) = " << phi << endl; | ||
66 | cout << "Public key (n, e): (" << n << ", " << e << ")\n"; | ||
67 | cout << "Private key (n, d): (" << n << ", " << d << ")\n"; | ||
68 | for (i = 0; i < len; i++) | ||
69 | cipher[i] = encrypt(text[i], n, e); | ||
70 | cout << "Encrypted message: "; | ||
71 | for (i = 0; i < len; i++) | ||
72 | cout << cipher[i]; | ||
73 | for (i = 0; i < len; i++) | ||
74 | text[i] = decrypt(cipher[i], n, d); | ||
75 | cout << endl; | ||
76 | cout << "Decrypted message: "; | ||
77 | for (i = 0; i < len; i++) | ||
78 | cout << text[i]; | ||
79 | cout << endl; | ||
80 | return 0; | ||
81 | } | ||