Search code examples
openssl

Backport EVP_PKEY_Q_KEYGEN to OpenSSL 1.1


I have some code built against OpenSSL 3.0 that I need to backport to OpenSSL 1.1. Unfortunately, one function that doesn't seem to have a direct analogue in 1.1 is EVP_PKEY_Q_keygen. How can I reasonably generate an EC private key in OpenSSL 1.1 that I can then use to generate a certificate signing request?

Essentially, I need the equivalent of this:

  EVP_PKEY *pkey =
      EVP_PKEY_Q_keygen(NULL, NULL, "EC", (char *)(strstr("prime256v1", "")));

Solution

  • The old high-level way, similar to what genpkey does:

    EVP_PKEY *pkey = NULL;
    EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_id (EVP_PKEY_EC,NULL); if( !ctx ) error;
    if( EVP_PKEY_keygen_init (ctx) <= 0 ) error;
    if( EVP_PKEY_CTX_set_ec_paramgen_curve_nid (OBJ_sn2nid("prime256v1")) <=0 ) error;
    /* even though spelled paramgen this is valid for keygen also */
    if( EVP_PKEY_keygen (ctx, &pkey) <= 0 ) error;
    

    The old low-level way, similar to what ecparam -genkey does:

    EC_KEY *ec = EC_KEY_new_by_curve_name("prime256v1"); if( !ec ) error; 
    if( EC_KEY_generate_key (ec) == 0 ) error;
    EVP_PKEY *pkey = EVP_PKEY_new(); if( !pkey ) error;
    if( EVP_PKEY_set1_EC_KEY (pkey, ec) == 0 ) error;
    EC_KEY_free (ec);
    

    Error handling left as an exercise, especially since you didn't show any yourself.