Working RSA, untested
This commit is contained in:
parent
32c54d892f
commit
344975bd8a
1 changed files with 34 additions and 27 deletions
51
main.c
51
main.c
|
@ -5,6 +5,7 @@
|
|||
#include <stdio.h>
|
||||
|
||||
#define LED_PIN PD6
|
||||
#define RSA_16
|
||||
|
||||
void exit_blink() {
|
||||
for (int i = 0; i < 4; i++) {
|
||||
|
@ -40,37 +41,43 @@ int main() {
|
|||
while (p == q) p = gen_prime(1 << 15, 1 << 16);
|
||||
|
||||
uint64_t n = p * q;
|
||||
uint64_t phi_n = (p - 1) * (q - 1);
|
||||
|
||||
int before = SysTick->CNT;
|
||||
bool check_a = miller_rabin(p, 10);
|
||||
int miller = SysTick->CNT - before;
|
||||
// 'e' is public. E for encrypt.
|
||||
uint64_t e = prand_range(3, phi_n - 1);
|
||||
while (gcd(e, phi_n) != 1) e = prand_range(3, phi_n - 1);
|
||||
|
||||
before = SysTick->CNT;
|
||||
bool check_b = is_prime(p);
|
||||
int isprime = SysTick->CNT - before;
|
||||
// 'd' is our private key. D as in decrypt
|
||||
uint64_t d = mod_inverse(e, phi_n);
|
||||
if (d == 0 || d == 1) {
|
||||
printf("Modular inverse not found...");
|
||||
while (1);
|
||||
}
|
||||
|
||||
printf("Is prime: %s %s\n", check_a ? "true" : "false",
|
||||
check_b ? "true" : "false");
|
||||
char msg[] = "Hello";
|
||||
uint64_t coded[sizeof(msg)] = {0};
|
||||
char decoded[sizeof(msg)] = {0};
|
||||
|
||||
printf("Miller took %d ticks\n", miller);
|
||||
printf("Is_prime took %d ticks\n", isprime);
|
||||
// Encode the message
|
||||
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("Q: %u\n", (uint32_t)q);
|
||||
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++) {
|
||||
funDigitalWrite(LED_PIN, p >> idx & 1);
|
||||
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);
|
||||
printf("Message: %s\n", msg);
|
||||
printf("Decoded: %s\n", decoded);
|
||||
}
|
||||
|
||||
// Exit and hang forever
|
||||
|
|
Loading…
Add table
Reference in a new issue