hmac.hh
Go to the documentation of this file.
#pragma once
#include <vector>
#include <openssl/hmac.h>
#include <openssl/objects.h>
enum class hash_algorithms: unsigned char {
sha_256,
sha_384
}; // End of class hash_algorithms
class hmac {
HMAC_CTX _ctx;
hash_algorithms _hash_algorithms;
public:
hmac(const hash_algorithms p_hash_algorithms): _ctx{}, _hash_algorithms(p_hash_algorithms) { ::HMAC_CTX_init(&_ctx); };
virtual ~hmac() { ::HMAC_CTX_cleanup(&_ctx); };
inline int generate(const std::vector<unsigned char> p_buffer, const std::vector<unsigned char> p_secret_key, std::vector<unsigned char>& p_hmac) {
// Sanity check
if (p_buffer.size() == 0) {
return -1;
}
return generate(p_buffer.data(), p_buffer.size(), p_secret_key.data(), p_secret_key.size(), p_hmac);
};
inline int generate(const unsigned char *p_buffer, const size_t p_buffer_length, const unsigned char *p_secret_key, const size_t p_secret_key_length, std::vector<unsigned char>& p_hmac) {
// Sanity check
if ((p_buffer == nullptr) || (p_secret_key == nullptr)) {
return -1;
}
p_hmac.resize(EVP_MAX_MD_SIZE);
if (_hash_algorithms == hash_algorithms::sha_256) {
::HMAC_Init_ex(&_ctx, (const void*)p_secret_key, (long unsigned int)p_secret_key_length, EVP_sha256(), NULL);
} else if (_hash_algorithms == hash_algorithms::sha_384) {
::HMAC_Init_ex(&_ctx, (const void*)p_secret_key, (long unsigned int)p_secret_key_length, EVP_sha384(), NULL);
} else { // TODO To be continued
return -1;
}
// Compute the hash value
::HMAC_Update(&_ctx, p_buffer, p_buffer_length);
unsigned int length = p_hmac.size();
::HMAC_Final(&_ctx, static_cast<unsigned char*>(p_hmac.data()), &length);
// Resize the hmac
if (_hash_algorithms == hash_algorithms::sha_256) {
p_hmac.resize(16);
} // FIXME Check length for the other hash algorithm
return 0;
};
}; // End of class hmac
hmac::hmac
hmac(const hash_algorithms p_hash_algorithms)
Default constructor Create a new instance of the hmac class.
Definition: hmac.hh:40
hmac::_ctx
HMAC_CTX _ctx
Definition: hmac.hh:32
hash_algorithms
hash_algorithms
Definition: hmac.hh:21
hmac::generate
int generate(const std::vector< unsigned char > p_buffer, const std::vector< unsigned char > p_secret_key, std::vector< unsigned char > &p_hmac)
Generate the HMAC of data using a secret key [in] p_buffer The data tobe hashed.
Definition: hmac.hh:55
hmac
This class provides description of HMAC helper methods.
Definition: hmac.hh:31
hash_algorithms::sha_256
hmac::generate
int generate(const unsigned char *p_buffer, const size_t p_buffer_length, const unsigned char *p_secret_key, const size_t p_secret_key_length, std::vector< unsigned char > &p_hmac)
Generate the HMAC of data using a secret key.
Definition: hmac.hh:75
hmac::~hmac
virtual ~hmac()
Default destructor.
Definition: hmac.hh:44
hash_algorithms::sha_384
hmac::_hash_algorithms
hash_algorithms _hash_algorithms
HMAC context.
Definition: hmac.hh:33