我正在尝试使用OpenSSL生成带有以下功能的RSA密钥:
RSA *genRSA() {
clear();
mvprintw(0, 0, "Generating RSA key...\n");
RAND_load_file("/dev/random", 4096);
BIGNUM *e = BN_new();
BN_set_word(e, RSA_F4);
RSA *rsa;
while (getch() != '\n'); // the program does reach this point
if (!RSA_generate_key_ex(rsa, 4096, e, 0)) { // seg fault must occur on this line
while (getch() != '\n'); // never gets here
printw("ERROR: Failed to create RSA key\n");
return NULL;
}
while (getch() != '\n'); // or here
BN_free(e);
if (!RSA_check_key(rsa)) {
printw("ERROR: Key failed validation\n");
return NULL;
}
printw("Key generation completed successfully\n");
return rsa;
}
我没有收到任何编译器警告,除了一些在OS X上被弃用的警告(这可能导致问题吗?)。为什么我会遇到段错?
答案 0 :(得分:2)
在不知道您正在使用的库的情况下,这是不正确的:
RSA *rsa;
while (getch() != '\n'); // the program does reach this point
if (!RSA_generate_key_ex(rsa, 4096, e, 0))
您正在使用未初始化的指针RSA_generate_key_ex
来呼叫rsa
。 RSA_generate_key_ex
函数无法使用它做任何事情,除非尝试使用它并且如您所见,崩溃。
因此,请阅读该函数的文档,了解第一个参数应该是什么。也许它应该是这样的:
RSA rsa;
while (getch() != '\n'); // the program does reach this point
if (!RSA_generate_key_ex(&rsa, 4096, e, 0))
如果是这种情况,那么您需要将返回类型更改为RSA
而不是RSA*
(我假设RSA
是类型的struct或typedef可以通过价值安全返回。