Migrating OpenSSL to EVP

Migrating OpenSSL to EVP

It has been years since I got the first warning that low-level OpenSSL functions are being deprecated. Recently I finally attempted to address the issue.

The popular ChatGPT had difficulty navigating the convoluted OpenSSL docs, so did I. But it did provided some pointers that helped me searching. So I finally had:

#include <openssl/hmac.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <openssl/core_names.h>

struct HMAC256{
    static constexpr size_t raw_size = 32;
    char result[65];//in hex
    size_t _sz;
    EVP_MAC *mac = EVP_MAC_fetch(NULL, OSSL_MAC_NAME_HMAC, NULL);
    EVP_MAC_CTX *ctx = EVP_MAC_CTX_new(mac);
    HMAC256(string_view k) {
        result[64]=0;

        OSSL_PARAM params[] = {
            OSSL_PARAM_construct_utf8_string(
                OSSL_MAC_PARAM_DIGEST,
                OSSL_DIGEST_NAME_SHA2_256,
                0),
            OSSL_PARAM_construct_end()};
        EVP_MAC_init(ctx, (const unsigned char *)k.data(), k.size(), params);
    }
    ~HMAC256() {
        EVP_MAC_CTX_free(ctx);
        EVP_MAC_free(mac);
    }
    const char *compute(string_view msg) {
        EVP_MAC_init(ctx, NULL, 0, NULL);
        EVP_MAC_update(ctx, (const unsigned char *)msg.data(), msg.size());
        EVP_MAC_final(ctx, (unsigned char *)result, &_sz, raw_size);
        FASSERT(_sz == raw_size);
        hexify(result, _sz);
        return result;
    }
};

Like some others I encountered some performance regression, very roughly 20%-40%, not as bad as several times, but still not ideal. So I am not deploying the change now, just keeping it in case they remove the low-level API I am using.


自制烤鸭 Encryption for secure online storage