【问题标题】:Segmentation Fault Generating RSA Key Using OpenSSL使用 OpenSSL 生成 RSA 密钥的分段错误
【发布时间】:2014-08-29 13:25:35
【问题描述】:

我正在尝试使用具有以下功能的 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 上已弃用的警告之外,我没有收到任何编译器警告(这会导致问题吗?)。为什么会出现段错误?

【问题讨论】:

  • 如果您确定它在 RSA_generate_key_ex() 函数中出现故障,那么很可能是您的输入参数。验证每个函数都符合函数的预期。
  • 这也可能是个问题:RAND_load_file("/dev/random", 4096);。您要的是字节,而不是位。还有很多。它可能会耗尽设备,并且您可能会阻塞很长时间。要实现相当于 4096 位的密钥,需要大约 140 位的安全级别。 140/8 = 17.5 字节:RAND_load_file("/dev/random", 18);.
  • @jww 幸运的是我没花太长时间,但我会考虑你的建议。
  • @cabellicar123 - 在这种情况下,RAND_load_file("/dev/random", 4096); 可能会失败。您应该检查返回值并回退到"/dev/urandom"
  • @jww 好的。会做。感谢您的建议。

标签: c openssl


【解决方案1】:

在不了解您正在使用的库的情况下,这是不正确的:

RSA *rsa;
while (getch() != '\n'); // the program does reach this point
  if (!RSA_generate_key_ex(rsa, 4096, e, 0))

您正在使用未初始化的指针 rsa 调用 RSA_generate_key_exRSA_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 是可以按值安全返回的类型的结构或 typedef )。

【讨论】:

  • 我发现我需要首先通过将行更改为 RSA *rsa = RSA_new(); 来初始化 RSA。感谢您的帮助!