0

我正在尝试使用 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 项目的一部分

4

1 回答 1

0

我发现需要播种随机生成器(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;
}
于 2020-06-02T11:30:41.457 回答