To start, I'm running Ubuntu 12.04 32-bit. This program does RSA pub key crypto by taking cin into a char buffer. Then, when I call my encrypt function, I get the following error:
GNU MP: Cannot allocate memory (size=1307836444)
Aborted (core dumped)
When I change the bit-size of the p,q keys I generate, the size in this run-time error increases. This error happens only after I call encrypt().
void generate_pq(mpz_t p, mpz_t q);
void compute_n(mpz_t n, const mpz_t p, const mpz_t q);
void compute_phiN(mpz_t phi_n, const mpz_t p, const mpz_t q);
void select_e(mpz_t e, mpz_t phi_n);
void compute_d(mpz_t d, mpz_t e, mpz_t phi_n);
void store_m(mpz_t m[], int& size);
void encrypt(mpz_t c[], mpz_t m[], const int size,
const mpz_t e, const mpz_t n);
void decrypt(mpz_t m2[], mpz_t c[], const int size,
const mpz_t d, const mpz_t n);
int main()
{
mpz_t p, q, n, phi_n, e, d;
mpz_inits(p, q, n, phi_n, e, d, NULL);
// 1. Generate p,q; compute n
generate_pq(p,q);
compute_n(n,p,q);
// 2. Compute phi(n)=(p-1)*(q-1)
compute_phiN(phi_n,p,q);
mpz_clear(p); mpz_clear(q);
// 3. Select encryption key e
select_e(e,phi_n);
// 4. Compute decryption key d
compute_d(d,e,phi_n);
// 5. m = message to be encrypted
mpz_t* m;
int size=0;
store_m(m,size);
// 6. c = encrypted message
mpz_t* c;
encrypt(c,m,size,e,n);
// 7. m2 = decrypted message
//mpz_t* m2;
//decrypt(m2,c,size,d,n);
return 0;
}
Compiled using...
g++ -o rsa partb.cc -lgmpxx -lgmp
I have tried using mpz_clear in the for-loops for m, c, and m2. No change. Here is the encrypt function:
void store_m(mpz_t m[], int& size)
{
printf("Message: ");
char* buffer = new char[128];
cin.getline(buffer,128);
size = strlen(buffer); //size = buffer
m = new mpz_t[size];
for(int i=0; i<size; i++) {
mpz_init(m[i]);
mpz_set_ui(m[i],(int)buffer[i]);
}
}
void encrypt(mpz_t c[], mpz_t m[], const int size,
const mpz_t e, const mpz_t n)
{ /* c = cipher */
c = new mpz_t[size];
for(int i=0; i<size; i++) {
mpz_init(c[i]);
mpz_powm(c[i],m[i],e,n);
mpz_clear(m[i]);
} /* c = m^e(mod n) */
}
Perhaps the issue is that I am not deallocating enough of the mpz_t's that I have declared and initialized? I tried clearing 2 or 3 of the mpz_t's but it didn't seem to have an effect. Please advise.
EDIT!!!!!!!!
Isolated the seg fault to this statement:
mpz_powm(c[i],m[i],e,n);