这是 previous question 的后续问题(现在实际问题不同了):
int main()
{
mpz_t p, q, n, phi_n, e, d;
mpz_inits(p, q, n, phi_n, e, d, NULL);
generate_pq(p,q);
compute_n(n,p,q);
compute_phiN(phi_n,p,q);
mpz_clear(p,q,NULL);
select_e(e,phi_n);
compute_d(d,e,phi_n);
mpz_clear(phi_n);
mpz_t* m;
int size=0;
store_m(m,size);
mpz_t* c;
encrypt(c,m,size,e,n);
return 0;
}
相关函数如下:
void store_m(mpz_t m[], int& size)
{ /* m = original message */
printf("\nMessage: ");
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]);
}
delete buffer;
}
void encrypt(mpz_t*& c, mpz_t m[], const int size,
const mpz_t e, const mpz_t n)
{ /* c = cipher */
cout << "1" << endl;
c = new mpz_t[size];
cout << "2" << endl;
for(int i=0; i<size; i++) {
cout << "3" << endl;
mpz_init(c[i]);
cout << "4" << endl;
mpz_powm(c[i],m[i],e,n);
cout << "5" << endl;
mpz_clear(m[i]);
cout << "6" << endl;
} /* c = m^e(mod n) */
cout << "7" << endl;
}
当我执行时,程序进入 encrypt() 但在第 4 个 cout 时出现段错误。
最佳答案
请记住,C++ 是按值传递的,除非您明确表示要使用 &
运算符按引用传递。在 store_m()
中,您正在函数内部分配给 m
。这是行不通的,因为您是按值传递 m
的。结果 main()
函数永远不会看到对 m
的赋值,因为 store_m()
只有 m< 的本地拷贝
。因此,您将未初始化的变量传递给 encrypt()
。在 main()
中分配 m
或像这样声明 store_m()
:
void store_m( mpt_t*& m, int& size);
顺便说一句:您没有在第 4 个 cout
发生段错误。在 encrypt()
函数准备调用 mpz_powm()
之后,您正在发生段错误。实际崩溃是取消引用 m[i]
(因为 m
已初始化)。
关于c++ - for循环中的RSA mpz_powm() : seg fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20131671/