I'm trying to write a simple program in C++ to demonstrate the math behind RSA. I'm using the GMP library ( https://gmplib.org/ ) so that I can scale it up later with larger primes.
When I attempt to calculate D, the decryption exponent, as the modular inverse of e mod phi(n), it segfaults and I have am lost as to why.
Can anyone shed some light on this issue?
#include <gmp.h> // For the GMP library
int main()
{
mpz_t n,p,q,e,c,d,h;
mpz_init(n);
mpz_init(h);
mpz_init_set_str(e, "65537", 10);
mpz_init_set_str(p, "1298849", 10);
mpz_init_set_str(q, "1298863", 10);
mpz_mul(n,p,q);
mpz_sub_ui(p, p, 1UL);
mpz_sub_ui(q, q, 1UL);
mpz_mul(h, p, q);
gmp_printf ("%Zd\n", h);
//This next line segfaults it.
mpz_invert(d,e,h);
return 0;
}
Any help is appreciated, I'm pretty stumped!
To Compile:
g++ -std=c++11 Example.cpp -lgmp -lgmpxx -o Example
You never initialized c
or d
, so you can't use them for calculation.