← Back to section · Tutorials & Labs
Wrapping Cryptographic Objects in RAII: Making Forget-to-Free Unwritable
Put C objects such as EVP_PKEY and OQS_KEM into std::unique_ptr with custom deleters, then write a self-wiping guard class for secret-key buffers, turning release and erasure from discipline into construction.
The Pain of C APIs: Every Branch Must Remember to Free
In the previous two articles every object needed a manually paired release: EVP_PKEY_free, EVP_PKEY_CTX_free, OQS_KEM_free, and secret keys needed a wipe before free. With a single exit point that is fine, but real code nests error branches, early returns and C++ exceptions; any path that misses a release leaks, any path that misses a wipe leaves secret residue, and a double release crashes outright. Auditing every path by hand does not scale. The proper fix is C++‘s signature technique, RAII (resource acquisition is initialization): bind an object’s lifetime to a scope and let the destructor do the teardown, which the compiler guarantees runs on every way out of the scope — normal return, error return, or exception. This article wraps the typical OpenSSL and liboqs objects one by one.
Step One: unique_ptr Plus a Deleter
Most OpenSSL and liboqs objects ship a release function of the form T_free(T *), which can serve directly as the deleter of a std::unique_ptr. The idiom is to alias the smart pointer with the release function’s pointer type as the deleter:
#include <memory>
#include <openssl/evp.h>
#include <oqs/oqs.h>
using EvpPkeyPtr = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using EvpCtxPtr = std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)>;
using OqsKemPtr = std::unique_ptr<OQS_KEM, decltype(&OQS_KEM_free)>;
EvpPkeyPtr keygen()
{
EvpCtxPtr ctx(EVP_PKEY_CTX_new_from_name(nullptr, "ML-KEM-768", nullptr),
&EVP_PKEY_CTX_free);
if (!ctx || EVP_PKEY_keygen_init(ctx.get()) <= 0)
return {nullptr, &EVP_PKEY_free};
EVP_PKEY *raw = nullptr;
if (EVP_PKEY_keygen(ctx.get(), &raw) <= 0)
return {nullptr, &EVP_PKEY_free};
return {raw, &EVP_PKEY_free}; // ctx is released automatically here
}
No hand-written _free call remains: whichever branch returns, ctx is released, and the smart pointer adopting raw carries the key’s release duty back to the caller. Note that the deleter is part of the type, so return types must spell out the full alias; and remember that unique_ptr forbids copying and allows moving by default, matching the C convention of “whoever holds it, frees it”. If some object has no ready-made _free function — a home-grown structure that needs a wipe before release, say — write a small function object as the deleter in exactly the same shape.
Step Two: Secret Buffers Need a Dedicated Guard
Plain buffers are fine in a std::vector<uint8_t>, but secret keys and shared secrets add one requirement: wipe before release. A vector destructor returns memory without erasing contents, so write a dedicated guard class that bakes “length” and “wipe, then free” into its destructor:
class SecretBuffer {
public:
explicit SecretBuffer(std::size_t n) : data_(new uint8_t[n]), size_(n) {}
~SecretBuffer() {
if (data_) {
OPENSSL_cleanse(data_, size_);
delete[] data_;
}
}
SecretBuffer(const SecretBuffer &) = delete;
SecretBuffer &operator=(const SecretBuffer &) = delete;
SecretBuffer(SecretBuffer &&o) noexcept : data_(o.data_), size_(o.size_) {
o.data_ = nullptr; o.size_ = 0;
}
uint8_t *data() { return data_; }
std::size_t size() const { return size_; }
private:
uint8_t *data_;
std::size_t size_;
};
Several choices here are deliberate. The wipe sits at the top of the destructor, so every path out of scope wipes before freeing. Copying is explicitly deleted, because every copy of a secret is another place that needs wiping, and in most designs secrets should never be copied at all. Moving is allowed, but the moved-from object is nulled, so exactly one owner is responsible for wiping each allocation. OPENSSL_cleanse can be swapped for the previous article’s OQS_MEM_cleanse; both guarantee the write is not optimized away, and the choice depends on which library the project mainly links. In use, a decapsulated shared secret goes straight into a SecretBuffer and vanishes automatically at scope exit — no hand-written wipe at every return point.
Step Three: Controlled Exits for the C API
Wrapping does not mean hiding the raw pointer forever; it means controlling how it crosses the boundary. Interfacing with C APIs needs only three controlled operations: get() lends the pointer for a read or a single call with ownership unchanged; release() hands ownership over to a C function that takes over the lifetime, leaving the wrapper empty; reset() destroys early and optionally adopts a new object. unique_ptr provides all three, and a home-grown class like SecretBuffer just mirrors them. Two common misuses must be avoided: storing the result of get() for long-term use — it dangles the moment the wrapper dies — and handing the same raw pointer to two smart pointers, which guarantees a double free at destruction. A useful team rule: in code review, grep for _free( and free( and demand a justification for every hit outside the wrapper layer; ideally business code contains none of these names at all.
Step Four: Reference-Counted Objects and Container Storage
One class of object does not fit the alias pattern directly: OpenSSL’s EVP_PKEY is itself reference-counted, and library internals plus multiple structures may share one key. That raises two practical issues. First, when keys are stored long-term in containers such as std::vector or std::map, the container must hold owning smart pointers, not raw pointers — otherwise the moment the original holder releases, the container’s pointer dangles. Second, when one key genuinely needs several references, the correct move is to call EVP_PKEY_up_ref to increment the reference count and let each referrer hold its own to-be-freed pointer — never hand the same raw pointer to two unique_ptrs, which guarantees a double free at destruction. The criterion for choosing a wrapper is the release function’s semantics: objects like OQS_KEM have no reference-count interface, so exclusive ownership via unique_ptr is exactly right; EVP_PKEY has up_ref, signalling that the library expects sharing, so the wrapper must spell out the exclusive and the shared-with-count cases separately. One more small pitfall: for objects returned by library functions, first establish whether you received a fresh reference or a borrowed one — an interface documented as returning a borrowed reference (some functions hand back an object owned by a context) must never be wrapped in unique_ptr, or you will free an object someone else is still using. These judgments can only be made per interface from the documentation; there is no shortcut. But a project only ever wraps a dozen or so interfaces — check them once, write the conclusion into comments at the alias definitions, and the team benefits permanently.
Summary
RAII wrapping has an excellent return on investment: one unique_ptr alias per C object and a few dozen lines for a secret-buffer guard convert the manual discipline of “remember to release and wipe on every branch” into a structural guarantee the compiler enforces. There is a bonus, too: object lifetimes become visible at a glance, and a reviewer can see where every resource ends just by scanning scopes. The next article covers the build side: linking OpenSSL and liboqs correctly into one project with CMake.
Tags: C++RAIIOpenSSLliboqs