Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
OpenSSL HMAC
#include <map>
#include <stdexcept>
#include <string>
#include <xtl/xbase64.hpp>
#pragma cling load("/srv/conda/lib/libcrypto.so")
#pragma cling load("/srv/conda/lib/libssl.so")
#include <openssl/hmac.h>
#include <openssl/sha.h>
std::string sign(const std::string& data, const std::string& signature_scheme = "hmac-sha256")
{
static const std::map<std::string, const EVP_MD*(*)()> alg = {
{"hmac-md5", EVP_md5},
{"hmac-sha1", EVP_sha1},
{"hmac-mdc2", EVP_mdc2},
{"hmac-ripemd160", EVP_ripemd160},
{"hmac-blake2b512", EVP_blake2b512},
{"hmac-blake2s256", EVP_blake2s256},
{"hmac-sha224", EVP_sha224},
{"hmac-sha256", EVP_sha256},
{"hmac-sha384", EVP_sha384},
{"hmac-sha512", EVP_sha512}
};
try
{
const EVP_MD* evp = alg.at(signature_scheme)();
}
catch (const std::out_of_range&)
{
throw std::runtime_error("Unrecognized signature scheme");
}
/*if (data.empty()) { throw std::invalid_argument("Data is empty"); }*/
HMAC_CTX *hmac;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
// OpenSSL 1.0.x
HMAC_CTX hmac_l;
HMAC_CTX_init(&hmac_l);
hmac = &hmac_l;
#else
hmac = HMAC_CTX_new();
#endif
auto mykey = "mykey";
HMAC_Init_ex(hmac, mykey, strlen(mykey), evp, nullptr);
HMAC_Update(hmac, reinterpret_cast<const uint8_t*>(data.c_str()), data.size());
auto res = new unsigned char[EVP_MD_size(evp)];
uint32_t size;
HMAC_Final(hmac, res, &size);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
// OpenSSL 1.0.x
HMAC_CTX_cleanup(hmac);
#else
HMAC_CTX_free(hmac);
#endif
return xtl::base64encode((char*)res);
}
std::string data = "hello";
sign(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.