added negative check for euclidian algo res and implemented crt

This commit is contained in:
2026-04-09 12:57:39 +02:00
parent aee2d7ffd0
commit 3473883507

52
main.c
View File

@@ -5,6 +5,7 @@
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>
#include "helper.c"
@@ -156,19 +157,45 @@ euklidian_result_t euklidian_algorigthm_extended(unsigned __int128 a, unsigned _
return res;
}
void kinai_maradek_tetel() {
unsigned __int128 kinai_maradek_tetel(uint64_t *m, uint64_t d, prime_test_t *p, prime_test_t *q) {
// sum(i: 1,2): Ci * Yi * Mi mod M
// M: P*Q, Mp: M/P, Mq: M/Q
unsigned __int128 M = p->prime * q->prime;
uint64_t Mp = q->prime;
uint64_t Mq = p->prime;
// C1: c^(d mod P-1) mod P
uint64_t temp_exponent = d % (p->prime - 1);
uint64_t m_bin_length = 0;
uint64_t *m_as_binary = dec_to_bin(*m, &m_bin_length);
uint64_t c1 = quick_pow(m_as_binary, p->base, p->prime, m_bin_length);
// C2: c^(d mod Q-1) mod Q
temp_exponent = d % (q->prime - 1);
uint64_t c2 = quick_pow(m_as_binary, q->base, q->prime, m_bin_length);
free(m_as_binary);
euklidian_result_t y = euklidian_algorigthm_extended(Mp, Mq); // in the struct the x will mean the y1 and y will mean the y2
// if either of them is less then 0 shift them into postive range with fi_n
while (y.x < 0) {
y.x += p->prime;
}
while (y.y < 0) {
y.y += q->prime;
}
return (c1 * y.x * Mp) + (c2 * y.y * Mq) % M;
}
unsigned __int128 rsa_encrypt(uint64_t *m, prime_test_t *p, prime_test_t *q) {
unsigned __int128 n = p->prime * q->prime;
printf("n: ");
print_uint128(n);
printf("\n");
unsigned __int128 fi_n = (p->prime - 1) * (q->prime - 1);
printf("fi_n: ");
print_uint128(fi_n);
printf("\n");
@@ -179,6 +206,13 @@ unsigned __int128 rsa_encrypt(uint64_t *m, prime_test_t *p, prime_test_t *q) {
} while (e <= 1 && e >= fi_n && prime_test(e, p->base)); // the p and q base is used everywhere anyways, i wont pass in another arg
euklidian_result_t calc_d = euklidian_algorigthm_extended(fi_n, e);
// if either of them is less then 0 shift them into postive range with fi_n
while (calc_d.x < 0) {
calc_d.x += fi_n;
}
while (calc_d.y < 0) {
calc_d.y += fi_n;
}
__int128 d = calc_d.y;
uint64_t length = 0;
@@ -192,9 +226,9 @@ unsigned __int128 rsa_encrypt(uint64_t *m, prime_test_t *p, prime_test_t *q) {
}
int main() {
uint64_t m = 0;
/*uint64_t m = 0;
printf("give input for m: \n");
scanf("%ju", &m);
scanf("%ju", &m);*/
srand(time(NULL));
@@ -210,5 +244,17 @@ int main() {
pthread_join(thread_q, NULL);
printf("\n");
// for testing i will overwrite the value
uint64_t m = 111;
p.prime = 107;
q.prime = 103;
rsa_encrypt(&m, &p, &q);
printf("\nkinai maradek tetel:\n");
unsigned __int128 S = kinai_maradek_tetel(&m, 2263, &p, &q);
printf("S: ");
print_uint128(S);
printf("\n");
return 0;
}