如何使用OpenSSL生成ECDHE公钥?

时间:2015-03-22 23:59:24

标签: c openssl elliptic-curve diffie-hellman

我尝试在Windows上使用OpenSSL 1.0.2a生成ECDHE密钥,并提供以下示例代码:

#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/ecdh.h>

int main()
{
    OpenSSL_add_all_algorithms(); ERR_load_crypto_strings();

    EVP_PKEY_CTX* parameters_context = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
    EVP_PKEY* cparameters = nullptr;
    EVP_PKEY* private_key = nullptr;

    if (EVP_PKEY_paramgen_init(parameters_context) != 1) { return 1; }
    if (EVP_PKEY_CTX_set_ec_paramgen_curve_nid(parameters_context, NID_sect571k1) != 1) { return 1; }
    if (EVP_PKEY_paramgen(parameters_context, &cparameters) != 1) { return 1; }

    EVP_PKEY_CTX* key_generation_context = EVP_PKEY_CTX_new(cparameters, NULL);

    if (!key_generation_context) { return 1; }
    if (EVP_PKEY_keygen_init(key_generation_context) != 1) { return 1; }        
    if (EVP_PKEY_keygen(key_generation_context, &private_key) != 1) { return 1; }

    BIO* bio = BIO_new(BIO_s_mem());
    PEM_write_bio_PUBKEY(bio, private_key); // <== This is where things go wrong.

    ERR_free_strings(); EVP_cleanup(); CRYPTO_cleanup_all_ex_data();
}

我在其他平台上测试了上述代码(OSX和Debian Linux,使用gcc),看起来工作正常(valgrind下没有报告错误)。

当我在Windows上运行它时,它总是在这一行上失败:

PEM_write_bio_PUBKEY(bio, private_key);

我得到了这个&#34;很好&#34;错误屏幕:

heap error

我很遗憾找出错误的地方:从我能找到的许多教程和文档页面来看,这似乎是正确的做事方式。

在我花了一天时间试图弄清楚什么是错的之前,我认为向社区提问可能更聪明:这是使用OpenSSL生成和编写ECDHE密钥作为PEM格式的正确方法吗?

1 个答案:

答案 0 :(得分:0)

这确实是OpenSSL中的一个错误。

来自OpenSSL-dev mailing-list

  

2015年3月31日星期二,****** *******写道:

     

&GT;

     
    

if(!combine)         * pval = NULL;

  
     

我建议删除上面的两行。结构应该是   没有这个清除,上面的行对非指针是错误的   不管怎么说。

     

史蒂夫。    - Stephen N. Henson博士。 OpenSSL项目核心开发人员。现在提供商业技术支持,请参阅:http://www.openssl.org

有关详细信息,另请参阅this other question

相关问题