DH_generate_key

Matt Caswell matt at openssl.org
Thu Dec 10 12:16:11 UTC 2020



On 09/12/2020 15:31, Matt Caswell wrote:
>> our application creates a new DH and using DH_generate_key()
> 
> How do you set up the DH parameters? Do you load them from a file or
> generate them in your application? Or some other way? Will it break your
> application if you swap to using different parameters, or must you
> retain support for the old ones?
> 
> The first step is to create an EVP_PKEY object containing the DH
> parameters. How to do that depends on the answers to the above questions.

Sunil emailed me directly (off list) and provided some code samples.

So you have some fixed "p" and "g" parameter values defined as static
unsigned char arrays, which you are currently converting to BIGNUMs
using "BN_bin2bn", and then assigning to "dh->p" and "dh->g" respectively.

The "g" value is just "2", so in the 3.0 equivalent you don't need to
convert that to a BIGNUM first. Some equivalent code to construct a DH
params object (called "param_key" in the code below) is:


    EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
    OSSL_PARAM_BLD *tmpl = NULL;
    OSSL_PARAM *params = NULL;
    EVP_PKEY *param_key = NULL;

    if (pctx == NULL || !EVP_PKEY_key_fromdata_init(pctx))
        goto err;

    if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
            || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
            || !OSSL_PARAM_BLD_push_uint(tmpl, OSSL_PKEY_PARAM_FFC_G, 2))
        goto err;

    params = OSSL_PARAM_BLD_to_param(tmpl);
    if (params == NULL || !EVP_PKEY_fromdata(pctx, &param_key, params))
        goto err;
 err:
    EVP_PKEY_CTX_free(pctx);
    OSSL_PARAM_BLD_free_params(params);
    OSSL_PARAM_BLD_free(tmpl);


You can then generate the key using the code sample I gave in my
previous email:

    EVP_PKEY *key = NULL;
    EVP_PKEY_CTX *gctx = EVP_PKEY_CTX_new_from_pkey(NULL, param_key, NULL);

    EVP_PKEY_keygen_init(gctx);
    EVP_PKEY_gen(gctx, &key);
    EVP_PKEY_print_private(bio_out, key, 0, NULL);
    ...
    EVP_PKEY_free(key);
    EVP_PKEY_CTX_free(gctx);



Hope that helps,

Matt


More information about the openssl-users mailing list