-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRSA.c
More file actions
75 lines (59 loc) · 1.45 KB
/
RSA.c
File metadata and controls
75 lines (59 loc) · 1.45 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
//RSA algorithm
#include <stdio.h>
int gcd(int a, int b)
{
while (b != 0)
{
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int mod_of_d(int e, int z)
{
int d = 1;
while ((e * d) % z != 1)
d++;
return d;
}
int modPower(int base, int exp, int mod)
{
int result = 1;
base = base % mod;
while (exp > 0)
{
if (exp % 2 == 1)
result = (result * base) % mod;
exp = exp / 2;
base = (base * base) % mod;
}
return result;
}
int main()
{
int p, q, n, z, d, e;
int message;
int encrypted, decrypted;
printf("Enter two prime numbers (p and q): ");
scanf("%d %d", &p, &q);
n = p * q;
z = (p - 1) * (q - 1);
printf("Enter a value for e (1 < e < %d) such that gcd(e, %d) = 1: ", z, z);
scanf("%d", &e);
if (gcd(e, z) != 1)
{
printf("Invalid e! It must be coprime with %d.\n", z);
return 1;
}
d = mod_of_d(e, z);
printf("\nPublic Key: (%d, %d)", n, e);
printf("\nPrivate Key: (%d, %d)\n", n, d);
printf("Enter message to encrypt (as integer < %d): ", n);
scanf("%d", &message);
encrypted = modPower(message, e, n);
printf("Encrypted message: %d\n", encrypted);
decrypted = modPower(encrypted, d, n);
printf("Decrypted message: %d\n", decrypted);
return 0;
}