Working RSA, untested

This commit is contained in:
Imbus 2025-02-12 23:06:19 +01:00
parent 32c54d892f
commit 344975bd8a

51
main.c
View file

@ -5,6 +5,7 @@
#include <stdio.h> #include <stdio.h>
#define LED_PIN PD6 #define LED_PIN PD6
#define RSA_16
void exit_blink() { void exit_blink() {
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
@ -40,37 +41,43 @@ int main() {
while (p == q) p = gen_prime(1 << 15, 1 << 16); while (p == q) p = gen_prime(1 << 15, 1 << 16);
uint64_t n = p * q; uint64_t n = p * q;
uint64_t phi_n = (p - 1) * (q - 1);
int before = SysTick->CNT; // 'e' is public. E for encrypt.
bool check_a = miller_rabin(p, 10); uint64_t e = prand_range(3, phi_n - 1);
int miller = SysTick->CNT - before; while (gcd(e, phi_n) != 1) e = prand_range(3, phi_n - 1);
before = SysTick->CNT; // 'd' is our private key. D as in decrypt
bool check_b = is_prime(p); uint64_t d = mod_inverse(e, phi_n);
int isprime = SysTick->CNT - before; if (d == 0 || d == 1) {
printf("Modular inverse not found...");
while (1);
}
printf("Is prime: %s %s\n", check_a ? "true" : "false", char msg[] = "Hello";
check_b ? "true" : "false"); uint64_t coded[sizeof(msg)] = {0};
char decoded[sizeof(msg)] = {0};
printf("Miller took %d ticks\n", miller); // Encode the message
printf("Is_prime took %d ticks\n", isprime); for (int i = 0; i < sizeof(msg); i++) {
coded[i] = (uint64_t)modexp((uint64_t)msg[i], e, n);
}
// Make these work by patching printf // Decode the message
for (int i = 0; i < sizeof(msg); i++) {
decoded[i] = (char)modexp(coded[i], d, n);
}
{
printf("P: %u\n", (uint32_t)p); printf("P: %u\n", (uint32_t)p);
printf("Q: %u\n", (uint32_t)q); printf("Q: %u\n", (uint32_t)q);
printf("N: %u\n", (uint32_t)n); printf("N: %u\n", (uint32_t)n);
printf("Phi_N: %u\n", (uint32_t)phi_n);
printf("Pubkey (e): %u\n", (uint32_t)e);
printf("Privkey (d): %u\n", (uint32_t)d);
for (int idx = 0; idx < 16; idx++) { printf("Message: %s\n", msg);
funDigitalWrite(LED_PIN, p >> idx & 1); printf("Decoded: %s\n", decoded);
Delay_Ms(200);
}
for (int idx = 0; idx < 16; idx++) {
funDigitalWrite(LED_PIN, q >> idx & 1);
Delay_Ms(200);
}
for (int idx = 0; idx < 16; idx++) {
funDigitalWrite(LED_PIN, n >> idx & 1);
Delay_Ms(200);
} }
// Exit and hang forever // Exit and hang forever