102 lines
2.8 KiB
C++
102 lines
2.8 KiB
C++
// load environment variables from .env file
|
|
#include <fstream>
|
|
#include <cstdlib>
|
|
#include <string>
|
|
#include <cstring>
|
|
|
|
#include <openssl/hmac.h>
|
|
#include <openssl/err.h>
|
|
|
|
void load_env(char const* path)
|
|
{
|
|
std::ifstream f(path);
|
|
std::string line;
|
|
while (std::getline(f, line))
|
|
{
|
|
if (line.empty() || line[0] == '#')
|
|
continue;
|
|
auto pos = line.find('=');
|
|
if (pos == std::string::npos)
|
|
continue;
|
|
|
|
std::string key = line.substr(0, pos);
|
|
std::string val = line.substr(pos + 1);
|
|
|
|
#ifdef _WIN32
|
|
_putenv_s(key.c_str(), val.c_str());
|
|
#else
|
|
setenv(key.c_str(), val.c_str(), 1);
|
|
#endif
|
|
}
|
|
}
|
|
|
|
// hex to byte helper function
|
|
int hex_to_bytes_upper(const char *hex, unsigned char *out, size_t out_size)
|
|
{
|
|
size_t i = 0;
|
|
while (hex[0] && hex[1])
|
|
{
|
|
if (i >= out_size)
|
|
return -1;
|
|
unsigned char h = hex[0];
|
|
unsigned char l = hex[1];
|
|
int hi = (h <= '9') ? (h - '0') : (h - 'A' + 10);
|
|
int lo = (l <= '9') ? (l - '0') : (l - 'A' + 10);
|
|
// minimal sanity check
|
|
if (hi < 0 || hi > 15 || lo < 0 || lo > 15)
|
|
return -1;
|
|
out[i++] = (unsigned char)((hi << 4) | lo);
|
|
hex += 2;
|
|
}
|
|
return (int)i;
|
|
}
|
|
|
|
char * byte_to_hex(unsigned char *bytes, size_t len)
|
|
{
|
|
char *hex = new char[len * 2 + 1];
|
|
for (size_t i = 0; i < len; i++)
|
|
{
|
|
sprintf(hex + i * 2, "%02X", bytes[i]);
|
|
}
|
|
hex[len * 2] = '\0';
|
|
return hex;
|
|
}
|
|
|
|
void cal_hmac(unsigned char *mac, char *message)
|
|
{
|
|
|
|
/* The secret key for hashing */
|
|
const char *key_str = getenv("HMAC_KEY");
|
|
if (key_str == NULL)
|
|
{
|
|
fprintf(stderr, "HMAC_KEY not set in environment\n");
|
|
return;
|
|
}
|
|
unsigned char key_char[64];
|
|
int key_len = hex_to_bytes_upper(key_str, key_char, sizeof(key_char));
|
|
if (key_len != 64) {
|
|
fprintf(stderr, "Invalid HMAC_KEY format\n");
|
|
return;
|
|
}
|
|
const char *key = (const char *)key_char;
|
|
// printf("HMAC key: %s\n", byte_to_hex((unsigned char *)key, key_len));
|
|
|
|
/* Change the length accordingly with your chosen hash engine.
|
|
* Be careful of the length of string with the chosen hash engine. For
|
|
example, SHA1 needed 20 characters. */
|
|
unsigned int len = 20;
|
|
/* Create and initialize the context */
|
|
HMAC_CTX *ctx = HMAC_CTX_new();
|
|
/* Initialize the HMAC operation. */
|
|
HMAC_Init_ex(ctx, key, key_len, EVP_sha1(), NULL);
|
|
/* Provide the message to HMAC, and start HMAC authentication. */
|
|
HMAC_Update(ctx, (unsigned char *)message, strlen(message));
|
|
/* HMAC_Final() writes the hashed values to md, which must have enough
|
|
space for the hash function output. */
|
|
HMAC_Final(ctx, mac, &len);
|
|
/* Releases any associated resources and finally frees context variable
|
|
*/
|
|
HMAC_CTX_free(ctx);
|
|
return;
|
|
}
|