← Back to section · Tutorials & Labs

The KEM Three-Step with liboqs in C: Key Generation, Encapsulation, Decapsulation

Starting from OQS_KEM_new, this tutorial walks through the full liboqs C API flow for key generation, encapsulation and decapsulation, covering buffer sizes, status checks and secret-memory hygiene.

Published 22 November 2026 · 7 min read · PQ Frontier

The KEM Three-Step with liboqs in C: Key Generation, Encapsulation, Decapsulation
AI-generated site artwork
Video explainer · PQC programming: calling real libraries

The Python bindings are convenient, but underneath them sits the liboqs C API. If you want to embed post-quantum algorithms into an existing C/C++ system, build a high-performance service, or simply understand what the binding layer is doing on your behalf, you cannot avoid this set of C functions. Using ML-KEM-768 as the example, this tutorial walks through the three steps of a key encapsulation mechanism (KEM) — key generation, encapsulation, decapsulation — and spells out the size, return-value and memory discipline at each step.

Note: liboqs is the research codebase of the Open Quantum Safe project, positioned by its authors for prototyping and algorithm evaluation. Do not lift an experimental build straight into production. The goal here is to learn the correct calling pattern.

Step one: obtain the algorithm object and confirm it is available

Every KEM operation in liboqs revolves around an OQS_KEM struct pointer. Create it by passing the algorithm name to OQS_KEM_new; if the algorithm was not compiled into your liboqs build, the function returns NULL. So before calling anything, confirm availability with OQS_KEM_alg_is_enabled and null-check the return of OQS_KEM_new — this is the most common crash site in the C API: skip the check, dereference the pointer, and the program dies mysteriously on someone else’s machine.

Once you have the object, never hardcode buffer sizes from memory. The OQS_KEM struct carries a family of length_ fields — length_public_key, length_secret_key, length_ciphertext, length_shared_secret — giving the exact byte counts for the public key, secret key, ciphertext and shared secret. Switch parameter sets (say from ML-KEM-768 to ML-KEM-1024) and all of these numbers change; code that allocates from the fields adapts to every parameter set for free.

Step two: the complete three-step code

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <oqs/oqs.h>

int main(void) {
    /* 1) Confirm the algorithm is enabled and create the object */
    if (OQS_KEM_alg_is_enabled("ML-KEM-768") == 0) {
        fprintf(stderr, "ML-KEM-768 is not enabled\n");
        return EXIT_FAILURE;
    }
    OQS_KEM *kem = OQS_KEM_new("ML-KEM-768");
    if (kem == NULL) {
        fprintf(stderr, "OQS_KEM_new failed\n");
        return EXIT_FAILURE;
    }

    /* 2) Allocate buffers using the sizes from the struct */
    uint8_t *public_key  = malloc(kem->length_public_key);
    uint8_t *secret_key  = malloc(kem->length_secret_key);
    uint8_t *ciphertext = malloc(kem->length_ciphertext);
    uint8_t *secret_enc  = malloc(kem->length_shared_secret);
    uint8_t *secret_dec  = malloc(kem->length_shared_secret);
    if (!public_key || !secret_key || !ciphertext || !secret_enc || !secret_dec) {
        fprintf(stderr, "allocation failed\n");
        return EXIT_FAILURE; /* production code should free what was allocated */
    }

    /* 3) Key generation: produces the public and secret keys */
    OQS_STATUS rc = OQS_KEM_keypair(kem, public_key, secret_key);
    if (rc != OQS_SUCCESS) {
        fprintf(stderr, "keypair failed\n");
        return EXIT_FAILURE;
    }

    /* 4) Encapsulation: the sender uses the public key to produce
          a ciphertext and a shared secret */
    rc = OQS_KEM_encaps(kem, ciphertext, secret_enc, public_key);
    if (rc != OQS_SUCCESS) {
        fprintf(stderr, "encaps failed\n");
        return EXIT_FAILURE;
    }

    /* 5) Decapsulation: the receiver recovers the shared secret
          from the ciphertext with the secret key */
    rc = OQS_KEM_decaps(kem, secret_dec, ciphertext, secret_key);
    if (rc != OQS_SUCCESS) {
        fprintf(stderr, "decaps failed\n");
        return EXIT_FAILURE;
    }

    /* 6) Constant-time comparison: both shared secrets must match */
    if (OQS_MEM_secure_bcmp(secret_enc, secret_dec,
                            kem->length_shared_secret) != 0) {
        fprintf(stderr, "shared secrets do not match\n");
        return EXIT_FAILURE;
    }
    printf("KEM three-step complete, shared secrets match (%zu bytes)\n",
           kem->length_shared_secret);

    /* 7) Wipe and free: secrets must not linger in memory */
    OQS_MEM_secure_free(secret_key, kem->length_secret_key);
    OQS_MEM_secure_free(secret_enc, kem->length_shared_secret);
    OQS_MEM_secure_free(secret_dec, kem->length_shared_secret);
    free(public_key);
    free(ciphertext);
    OQS_KEM_free(kem);
    return EXIT_SUCCESS;
}

Build it by linking against liboqs (adjust include and library search paths to your installation):

gcc -O2 -Wall kem_demo.c -o kem_demo -loqs
./kem_demo

Note that the parameter order of the three functions is not perfectly symmetric: in OQS_KEM_encaps the outputs come first — ciphertext, then shared secret — with the public key last; in OQS_KEM_decaps the shared secret comes first, followed by the ciphertext and the secret key. Swap them and the compiler will not complain (everything is uint8_t *), but you will get garbage at runtime — which is exactly why you should check the prototypes in oqs/kem.h character by character.

While you are here, meet a few more fields of the struct that prove invaluable in debugging and logging: method_name is the algorithm name string, alg_version is the specification version string the implementation follows, claimed_nist_level gives the claimed NIST security level, and ind_cca flags whether the KEM claims IND-CCA security. Print all four into your startup log and you defuse a particularly sneaky class of problem: a machine with several liboqs builds installed (say, one from the system package manager and one compiled by hand) where the linker picked the wrong library — nothing errors, but the behavior is not the version you think it is. With the algorithm name, version and level in the startup log, you can confirm at a glance which implementation was actually loaded. This extends the “sizes from fields” discipline one step further: whatever the library already tells you through the struct, never rely on memory or assumption — read it out and use it.

Step three: return values and implicit rejection

OQS_KEM_keypair, OQS_KEM_encaps and OQS_KEM_decaps all return OQS_STATUS: OQS_SUCCESS on success, OQS_ERROR on failure. The discipline is simple: check every step, and if anything is not OQS_SUCCESS, abort the flow and release resources immediately instead of marching on with uninitialized buffers.

There is one semantic that trips up almost every newcomer: when a ciphertext has been tampered with, OQS_KEM_decaps does not return an error. It quietly produces a shared secret that looks perfectly normal — this is ML-KEM’s implicit rejection, designed so attackers get no oracle telling them whether a ciphertext was valid. So “decaps did not error” does not mean “both sides agree on the secret”; the protocol layer must perform key confirmation with that secret (for example by exchanging a MAC) to detect a mismatch.

Common mistakes checklist

  1. Not checking the return of OQS_KEM_new. If the algorithm is not built into the library it returns NULL, and every subsequent call is undefined behavior.
  2. Hardcoding buffer sizes from memory. ML-KEM-768 has a 1184-byte public key and a 1088-byte ciphertext, but ML-KEM-1024 changes all the numbers; always take sizes from the length_ fields.
  3. Comparing shared secrets with memcmp. A plain comparison returns at the first differing byte and leaks timing information; use liboqs’s constant-time OQS_MEM_secure_bcmp.
  4. Freeing secret keys with plain free. Secret keys and shared secrets should be wiped before release — OQS_MEM_secure_free exists precisely for this; a bare free leaves key material sitting in heap memory, waiting to be reused or dumped.
  5. Leaking resources on error paths. The sample above returns directly from failure branches for brevity; real engineering code should funnel everything through a single cleanup exit that frees all buffers and the algorithm object.

Wrap the three steps into your own function

Real projects do not scatter this flow through a main function; wrap it into a small function parameterized by algorithm name: internally it performs the availability check, object creation, allocation, the three calls and cleanup, and outwardly it hands over only the shared secret and ciphertext, returning a unified error code on failure. The benefits are twofold: call sites stay clean, with no repeated OQS_STATUS handling or release logic in business code; and switching parameter sets or algorithms later touches exactly one place, invisible to every caller. Mind two boundaries when wrapping: document in the function’s contract who allocates the shared-secret output buffer and who wipes and frees it, and keep that consistent project-wide; and make error codes carry enough information to distinguish at least “algorithm unavailable”, “out of memory” and “algorithm call failed” — never crush every failure into a single number.

Summary

The C API calling skeleton compresses into one sentence: fetch the object by name, size memory from its fields, check the status of all three steps, and wipe secrets when done. Once this discipline becomes instinct, neither switching to signatures (the OQS_SIG family mirrors this structure exactly) nor switching parameter sets requires major code changes. As a next exercise, change the argument of OQS_KEM_new to ML-KEM-512 and ML-KEM-1024, print the four length_ fields for all three parameter sets, and verify them against the parameter tables in FIPS 203 by hand.

Tags: liboqsCML-KEMProgramming