EVP Key and Parameter Generation
From OpenSSLWiki
Jump to navigationJump to search
The EVP functions support the ability to generate parameters and keys if required for EVP_PKEY objects.
Parameter Generation
Parameter generation is supported for the following EVP_PKEY types only:
- EVP_PKEY_EC (for ECDSA and ECDH keys)
- EVP_PKEY_DSA
- EVP_PKEY_DH
The following sample code shows an example of how to generate parameters for each of these key types:
/* Create the context for generating the parameters */ if(!(pctx = EVP_PKEY_CTX_new_id(type, NULL))) goto err; if(!EVP_PKEY_paramgen_init(pctx)) goto err; /* Set the paramgen parameters according to the type */ switch(type) { case EVP_PKEY_EC: /* Use the NID_X9_62_prime256v1 named curve - defined in obj_mac.h */ if(!EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, NID_X9_62_prime256v1)) goto err; break; case EVP_PKEY_DSA: /* Set a bit length of 2048 */ if(!EVP_PKEY_CTX_set_dsa_paramgen_bits(pctx, 2048)) goto err; break; case EVP_PKEY_DH: /* Set a prime length of 2048 */ if(!EVP_PKEY_CTX_set_dh_paramgen_prime_len(pctx, 2048)) goto err; } /* Generate parameters */ if (!EVP_PKEY_paramgen(pctx, ¶ms)) goto err;
Key Generation
The following sample code shows an example of how to generate keys with the exception of EVP_PKEY_HMAC and EVP_PKEY_CMAC keys:
if(*params != NULL) { if(!(kctx = EVP_PKEY_CTX_new(params, NULL))) goto err; } else { /* Create context for the key generation */ if(!(kctx = EVP_PKEY_CTX_new_id(type, NULL))) goto err; } /* RSA keys set the key length during key generation rather than parameter generation! */ if(type == EVP_PKEY_RSA) { if(!EVP_PKEY_CTX_set_rsa_keygen_bits(kctx, 2048)) goto err; } /* Generate the key */ if(!EVP_PKEY_keygen_init(kctx)) goto err; if (!EVP_PKEY_keygen(kctx, &key)) goto err;
CMAC keys are generated in a simlar fashion:
if(!(kctx = EVP_PKEY_CTX_new_id(type, NULL))) goto err; if(!EVP_PKEY_keygen_init(kctx)) goto err; /* Set the cipher to be used for the CMAC */ if (EVP_PKEY_CTX_ctrl(kctx, -1, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_CIPHER, 0, (void *)EVP_aes_256_ecb()) <= 0) goto err; /* Set the key data to be used for the CMAC */ if (EVP_PKEY_CTX_ctrl(kctx, -1, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_SET_MAC_KEY, /*key length*/32, "01234567890123456789012345678901") <= 0) goto err;
/* Generate the key */ if (!EVP_PKEY_keygen(kctx, &key)) goto err;
HMAC keys can be generated in the same way as for CMAC keys but do not take a cipher. A convenience function which wraps this process exists to simplify HMAC key generation:
key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, "password", strlen("password"));