#include "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) { for (int try = 0; try < 1000; try++) { if (try % 100 == 0) printf("try: %d\n", try); 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) { p = generate_prime(); q = generate_prime(); ln = (p - 1) * (q - 1); } if (q > p) { uint64_t tmp = p; p = q; q = tmp; } int64_t n = p * q; int64_t r0 = e; int64_t r1 = ln; 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; } int64_t d = euler(e, ln) + ln; if (d > n) { d -= ln; } /* printf("p: %ld\n", p); printf("q: %ld\n", q); printf("ln: %ld\n", ln); printf("n: %ld\n", n); printf("d: %ld\n", d); printf("e: %ld\n", e); printf("d * e %% ln = %ld\n", (d*e)%ln);*/ for (uint64_t m = 0; m < 16384; m++) { //uint64_t m = get_random_bytes(fd2); uint64_t c = pow_mod(m, e, n); uint64_t m2 = pow_mod(c, d, n); if (m != m2) { printf("ERROR try: %d\nround: n/a\nmsg: %ld\ncypher: %ld\ndecrypted: %ld\nd: %ld\ne: %ld\np: %lu\nq: %lu\nn: %lu\n", try, m, c, m2, d, e, p, q, n); break; } } //int64_t m = 42; /* for (int64_t m = 41; m < 43; m++) { int64_t c = pow_mod(m, e, n); int64_t m2 = pow_mod(c, d, n); if (d < 0) { int64_t c2 = euler(c, n); printf("c2: %ld\n", c2); printf("c2 * c %% n = %ld\n", ((c2 + n)*c)%n); printf("c2 * c %% n = %ld\n", ((c2)*c)%n); m2 = pow_mod(c2 + n, -d, n); } printf("message: %ld\n", m); printf("cypher: %ld\n", c); printf("decrypted: %ld\n", m2); }*/ } rsa_t rsa; rsa.p.len = 42; return rsa; }