简体   繁体   中英

How to generate an ECDHE public key with OpenSSL?

I'm trying to generate an ECDHE key using OpenSSL 1.0.2a on Windows and have the following sample code:

#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();
}

I tested the said code on other platforms (OSX and Debian Linux, using gcc ) and it seems works fine (no errors reported under valgrind ).

When I run it on Windows, it always fails on this line:

PEM_write_bio_PUBKEY(bio, private_key);

And I get this "nice" error screen:

堆错误

I'm at loss figuring out what is wrong: from the many tutorials and documentation pages I could find, this seems to be the right way of doing things.

Before I spend another day trying to figure out what's wrong, I figured it might smarter to ask the community: is this the right way of generating and writing an ECDHE key as PEM format with OpenSSL ?

It was indeed a bug in OpenSSL.

From the OpenSSL-dev mailing-list :

On Tue, Mar 31, 2015, ****** ******* wrote:

>

if (!combine) *pval = NULL;

I'd suggest deleting the two lines above. The structure should be cleared without this and the above line is wrong for non pointer fields anyway.

Steve. -- Dr Stephen N. Henson. OpenSSL project core developer. Commercial tech support now available see: http://www.openssl.org

See also this other question for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM