RSA_generate_key_ex 函数调用中的 RSA 密钥生成错误

RSA key generation error in RSA_generate_key_ex function call

我正在尝试使用 openssl 生成 RSA 密钥。我在 RSA_generate_key_ex 上遇到错误,不知道为什么会发生错误。

我合并了 ERR_get_error()ERR_error_string(),我得到了下一条消息:error:2506906C:lib(37):func(105):reason(108)。我还发现 108 错误代码意味着 RSA_R_DATA_GREATER_THAN_MOD_LEN

我正在尝试使用下面的 C 代码生成 RSA 密钥。为了简洁起见,我减少了免费调用和错误输出

RSA* generateRSA()
{
  BIGNUM *bne = BN_new();
  if (bne == NULL)
  {
    return NULL;
  }
  if (BN_set_word(bne, RSA_F4) != 1)
  {
    return NULL;
  }

  RSA *r = RSA_new();
  if (r == NULL)
  {
    return NULL;
  }
  // THERE I'VE GOT ERROR
  if (RSA_generate_key_ex(r, 2048, bne, NULL)!= 1)
  {
    // ERR_get_error() returns 2506906C
    // ERR_error_string() gives me RSA_R_DATA_GREATER_THAN_MOD_LEN
    return NULL;
  }

  return r;
}

问题是错误是什么意思,我该如何解决?

编辑:我使用 OpenSSL 1.1.0e 2017 年 2 月 16 日。我将其用作 EDK II Project

的一部分

我发现需要播种随机生成器(openssl 版本 1.0.2 和 1.1.0 随机生成器必须明确播种)。

我检查RAND_status()。它返回0。所以解决方案是在密钥生成之前添加RAND_seed()

const void* getSeedBuffer(int num);

RSA* generateRSA()
{
  RAND_seed(getSeedBuffer(1000), 1000); // don't forget to free memory
  BIGNUM *bne = BN_new();
  if (bne == NULL)
  {
    return NULL;
  }
  if (BN_set_word(bne, RSA_F4) != 1)
  {
    return NULL;
  }

  RSA *r = RSA_new();
  if (r == NULL)
  {
    return NULL;
  }
  if (RSA_generate_key_ex(r, 2048, bne, NULL)!= 1)
  {
    return NULL;
  }

  return r;
}