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
|
#include <math.h>
#include <stdio.h>
#include <assert.h>
long qe2(long x, long y, long n) /* berechne x^y mod n */
{
long s, t, u;
s = 1, t = x, u = y;
while (u) {
if (u & 1) s = (s * t) % n;
u >>= 1;
t = (t * t) % n;
}
return s;
}
void extended_euclid(long a, long b, long *x, long *y, long *d) /* erweiterter Euklid */
{
long q, r, x1 = 0, x2 = 1, y1 = 1, y2 = 0;
if (b == 0) {
*d = a;
*x = 1;
*y = 0;
return;
}
while (b > 0) {
q = a / b;
r = a - q * b;
*x = x2 - q * x1;
*y = y2 - q * y1;
a = b;
b = r;
x2 = x1;
x1 = *x;
y2 = y1;
y1 = *y;
}
*d = a;
*x = x2;
*y = y2;
}
long inverse(long a, long n)
{
long d, x, y;
extended_euclid(a, n, &x, &y, &d);
if (d == 1) return x;
return 0;
}
extern "C" long __declspec(dllexport) rsa_genkey(long p, long q, long e)
{
return inverse(e, (p-1)*(q-1));
}
extern "C" long __declspec(dllexport) rsa_encrypt(long m, long e, long n)
{
assert(m < n); /* m muss kleiner als n sein */
return qe2(m, e, n);
}
extern "C" long __declspec(dllexport) rsa_decrypt(long c, long d, long n)
{
assert(c < n); /* c muss kleiner als n sein */
return qe2(c, d, n);
}
|