← Back to section · Tutorials & Labs
OpenSSL EVP Usage Patterns: From Key Generation to Key Encapsulation
Use OpenSSL 3.x's high-level EVP interface to generate ML-KEM keys, encapsulate and decapsulate, with a clear account of context objects, parameter passing and error handling — the three things most often gotten wrong.
Why Everything Goes Through the EVP Layer
Every algorithm in OpenSSL also has a low-level interface, but those interfaces churn between versions and their signatures are mutually incompatible. The EVP (envelope) layer is the officially maintained high-level abstraction: whatever the underlying algorithm — RSA, EC or ML-KEM — a key is uniformly an EVP_PKEY and operations run through context objects. With the provider architecture introduced in OpenSSL 3.0, algorithm implementations moved into pluggable providers and the EVP layer fetches algorithms by name. The practical consequence is that the same code can switch to a post-quantum algorithm by changing the algorithm name string from RSA to ML-KEM-768, with almost no change to the surrounding logic. Since OpenSSL 3.5 the default provider includes standard implementations of ML-KEM (FIPS 203) and ML-DSA (FIPS 204), so this pattern now covers post-quantum algorithms end to end. This tutorial uses ML-KEM-768 key encapsulation to walk through the EVP patterns in detail.
Pattern One: Context Objects and Two-Phase Calls
Every EVP operation follows the same rhythm: create a context, initialize it, perform the operation, then free the context. Key generation uses EVP_PKEY_CTX, signing and digesting use EVP_MD_CTX, and symmetric encryption uses EVP_CIPHER_CTX — the naming is consistent. The two-phase shape exists so parameters have somewhere to live: the algorithm name, key size and digest choice are supplied at initialization time, either as an OSSL_PARAM array or through dedicated setters, and the execution phase only deals with inputs and outputs. Here is the skeleton for ML-KEM key generation, using only real interfaces:
#include <openssl/evp.h>
#include <openssl/err.h>
EVP_PKEY *mlkem_keygen(void)
{
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_name(NULL, "ML-KEM-768", NULL);
if (ctx == NULL)
return NULL;
if (EVP_PKEY_keygen_init(ctx) <= 0)
goto done;
if (EVP_PKEY_keygen(ctx, &pkey) <= 0) {
EVP_PKEY_free(pkey);
pkey = NULL;
}
done:
EVP_PKEY_CTX_free(ctx);
return pkey;
}
Note three details. First, the first argument of EVP_PKEY_CTX_new_from_name is the library context (NULL selects the default) and the third is a property query string, which can restrict the fetch to the FIPS provider. Second, the return-value convention is uniformly “less than or equal to zero means failure” — do not test only for == 0. Third, on success EVP_PKEY_keygen writes the new key through its output parameter, but on failure the output may already have been assigned, so the error path must also call EVP_PKEY_free. Initializing pkey to NULL and freeing it on the failure branch is the safest shape.
Pattern Two: KEM Encapsulation and Decapsulation
Key encapsulation is an operation class that was only completed in the 3.x series, exposed as EVP_PKEY_encapsulate_init, EVP_PKEY_encapsulate and the matching EVP_PKEY_decapsulate pair. Their calling convention has one easy trap: output buffers follow a “ask for the length first, then fetch the data” two-call idiom. On the first call you pass NULL for the output pointer and the function only fills in the required length; after allocating a buffer of that size, the second call actually writes the data. Encapsulation looks like this:
/* pkey holds the public key; ct/ss are output buffers */
size_t ct_len = 0, ss_len = 0;
EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_pkey(NULL, pkey, NULL);
EVP_PKEY_encapsulate_init(ctx, NULL);
EVP_PKEY_encapsulate(ctx, NULL, &ct_len, NULL, &ss_len); /* ask length */
unsigned char *ct = OPENSSL_malloc(ct_len);
unsigned char *ss = OPENSSL_malloc(ss_len);
EVP_PKEY_encapsulate(ctx, ct, &ct_len, ss, &ss_len); /* fetch data */
Decapsulation is perfectly symmetric: build a context from the EVP_PKEY holding the private key, call EVP_PKEY_decapsulate_init, then run EVP_PKEY_decapsulate with the ciphertext as input to recover the shared secret. One semantic point deserves emphasis — ML-KEM’s implicit rejection: if the ciphertext was tampered with, decapsulation does not fail; it returns a random-looking fake secret, and the session keys derived from it simply will not match, so the handshake fails later. This is FIPS 203 working as designed, not a bug. Never treat “decapsulation returned success” as evidence that the peer is trustworthy; authentication must come from the key-confirmation step that follows.
Pattern Three: You Must Read the Error Queue
OpenSSL error handling is a thread-local error queue: when a function fails, the reasons are queued as error records and must be drained with ERR_get_error and rendered with ERR_error_string_n. While debugging, the shortcut is ERR_print_errors_fp(stderr), which prints the whole queue. Production code should at least drain the queue and log the first reason; otherwise all you will ever see in the field is a mysterious “returned 0”. Two further engineering habits are worth forming from day one. First, wipe key material obtained from EVP with OPENSSL_cleanse before freeing it — a companion article in this column covers wiping and constant-time comparison in depth. Second, wrap objects that come with a _free function, such as EVP_PKEY and EVP_PKEY_CTX, in RAII or a unified cleanup path as early as possible: the more error branches hand-write their frees, the higher the chance of leaks and double frees. A dedicated article in this column covers RAII wrapping.
Pattern Four: Pin the Provider with Property Queries
One more 3.x capability that tutorials often skip but compliance scenarios require: property queries. The same algorithm may exist in both the default provider and the FIPS provider, and the third argument of EVP_PKEY_CTX_new_from_name is the filter — passing "fips=yes" forces the fetch to take only the FIPS-validated implementation, and to fail outright rather than silently fall back if none is available. For projects facing a compliance audit, that string is more reliable than any verbal convention. Two related interfaces are worth knowing: OSSL_PROVIDER_load explicitly loads a provider (for instance loading the default and FIPS providers side by side from a configuration file), and EVP_set_default_properties sets default properties for a whole library context, so every later fetch without explicit properties inherits the same constraint. The engineering advice is to set the property policy once, at program startup, from configuration — never scatter it across call sites: nine call sites writing fips=yes and one forgetting it makes for a very ugly audit. Note also that properties only decide which provider supplies the implementation; they do not change the algorithm’s parameters or semantics, and fetching from the wrong provider normally surfaces as an initialization failure rather than wrong results, which is reassuring.
A closing exercise is worth more than another read-through: type out this article’s key-generation and encapsulation code by hand, then deliberately change the algorithm name to a nonexistent string, and separately restrict the fetch to an unloaded FIPS provider, and observe at which step each failure occurs and how the reasons in the error queue differ. Walking the failure paths builds a far truer feel for this interface than rerunning the success path — production incidents only ever meet you on the failure paths.
Summary
The EVP pattern compresses into three sentences: build a context first and execute in two phases; ask for buffer lengths before fetching data; check every return value and read the error queue. Once those are muscle memory, switching the algorithm name to ML-DSA gives you the signing flow (EVP_DigestSignInit, EVP_DigestSign) in the same rhythm, with EVP_MD_CTX as the context. A good next step is the liboqs companion article in this column, to see what the same task looks like in the other mainstream post-quantum library.
Tags: OpenSSLEVPML-KEMC