AES-DH Implementation
Loading...
Searching...
No Matches
hmac.h
1#pragma once
2
3#include <stdexcept> // For exceptions
4#include <string> // For std::string.
5
6#include <openssl/hmac.h> // For the HMAC function
7#include <openssl/evp.h> // For EVP_sha256()
8
14namespace hmac {
15 // Create our buffer for OpenSSL to dump the value to.
16 unsigned char md_value[EVP_MAX_MD_SIZE];
17 unsigned int md_len = 0;
18
30 std::string generate(const std::string& message, const std::array<uint64_t, 4>& key, const size_t& rounds) {
31
32 // Get the size of the key we use based on the rounds.
33 int key_size = sizeof(uint64_t);
34 int keys = 0;
35 switch (rounds) {
36 case 10: keys = 2; break;
37 case 12: keys = 3; break;
38 case 14: keys = 4; break;
39 default: throw std::runtime_error("Invalid round count!");
40 }
41
42 // Translate our 64 bit keys into a character array.
43 std::string key_bytes;
44 for (size_t x = 0; x < keys; ++x) {
45 auto num = key[x];
46
47 // Mask the byte, then shift to the next.
48 for (size_t y = 0; y < key_size; ++y, num >>= 1) {
49 key_bytes += char(num & 0xf);
50 }
51 }
52
53 // Generate the HMAC. Since this is more auxiliary to the main program, I won't dwell too long explaining this,
54 // but in essence OpenSSL deals with character arrays, specifically unsigned character arrays. For convenience,
55 // We deal with std::strings, which are signed characters. Therefore, we need to do some reinterpret casting
56 // To convert these signed values to unsigned values.
57 if (HMAC(EVP_sha256(), reinterpret_cast<const unsigned char*>(key_bytes.c_str()), key_bytes.length(), reinterpret_cast<const unsigned char*>(message.c_str()), message.length(), &md_value[0], &md_len) == NULL)
58 throw std::runtime_error("Failed to generate HMAC!");
59
60 // Same as above. We need to reinterpret the output values as "signed" characters
61 return std::string(reinterpret_cast<const char*>(&md_value[0]), md_len);
62 }
63}
This namespace includes the functions needed to generate an HMAC value Using OpenSSL.
Definition hmac.h:14
std::string generate(const std::string &message, const std::array< uint64_t, 4 > &key, const size_t &rounds)
Generate an HMAC for a message.
Definition hmac.h:30