59 lines
892 B
C
59 lines
892 B
C
#include "../includes/rsa.h"
|
|
|
|
int64_t euler(int64_t r0, int64_t r1) {
|
|
int64_t s0 = 1;
|
|
int64_t s1 = 0;
|
|
int64_t t0 = 0;
|
|
int64_t t1 = 1;
|
|
int64_t q0 = 0;
|
|
|
|
while (r1 != 0) {
|
|
q0 = r0 / r1;
|
|
int64_t tmp = r0 % r1;
|
|
r0 = r1;
|
|
r1 = tmp;
|
|
tmp = s0 - q0 * s1;
|
|
s0 = s1;
|
|
s1 = tmp;
|
|
tmp = t0 - q0 * t1;
|
|
t0 = t1;
|
|
t1 = tmp;
|
|
}
|
|
return s0;
|
|
}
|
|
|
|
rsa_t rsa_generate_keys(void) {
|
|
|
|
int64_t n = 0;
|
|
int64_t p = (uint64_t)generate_prime();
|
|
int64_t q = (uint64_t)generate_prime();
|
|
int64_t ln = (p - 1) * (q - 1);
|
|
int64_t e = 11317;
|
|
|
|
|
|
while (ln % e == 0 || p == q || !(n & (1 << 31))) {
|
|
p = generate_prime();
|
|
q = generate_prime();
|
|
ln = (p - 1) * (q - 1);
|
|
n = p * q;
|
|
}
|
|
|
|
if (q > p) {
|
|
uint64_t tmp = p;
|
|
p = q;
|
|
q = tmp;
|
|
}
|
|
|
|
int64_t d = euler(e, ln) + ln;
|
|
if (d > n) {
|
|
d -= ln;
|
|
}
|
|
rsa_t rsa;
|
|
rsa.d = d;
|
|
rsa.n = n;
|
|
//rsa.d = 104320933;
|
|
//rsa.n = 2959006679;
|
|
return rsa;
|
|
}
|
|
|