Skip to content

Instantly share code, notes, and snippets.

@rfl890
Created July 3, 2023 15:06
Show Gist options
  • Save rfl890/579a7d168fb0e9dca350e96777c48dcc to your computer and use it in GitHub Desktop.
Save rfl890/579a7d168fb0e9dca350e96777c48dcc to your computer and use it in GitHub Desktop.
Shitty openssl hmac
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#pragma comment (lib, "crypt32")
#pragma comment(lib, "ws2_32")
#pragma comment(lib, "user32")
#pragma comment(lib, "advapi32")
void handleErrors(void) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
void hmac(const unsigned char *msg, size_t msgLen, const unsigned char *key, size_t keyLen, unsigned char *out, size_t *outLen, size_t outsize) {
EVP_MAC *mac;
EVP_MAC_CTX *ctx;
OSSL_PARAM params[2];
size_t len = 0;
params[0] = OSSL_PARAM_construct_utf8_string("digest", "SHA3-256", 0);
params[1] = OSSL_PARAM_construct_end();
mac = EVP_MAC_fetch(NULL, "HMAC", NULL);
if (mac == NULL) {
handleErrors();
}
ctx = EVP_MAC_CTX_new(mac);
if (ctx == NULL) {
EVP_MAC_free(mac);
handleErrors();
}
if (!EVP_MAC_init(ctx, key, keyLen, params)) {
EVP_MAC_free(mac);
EVP_MAC_CTX_free(ctx);
handleErrors();
}
if (!EVP_MAC_update(ctx, msg, msgLen)) {
EVP_MAC_free(mac);
EVP_MAC_CTX_free(ctx);
handleErrors();
}
if (!EVP_MAC_final(ctx, out, &len, outsize)) {
EVP_MAC_free(mac);
EVP_MAC_CTX_free(ctx);
handleErrors();
}
EVP_MAC_free(mac);
EVP_MAC_CTX_free(ctx);
}
int main(void) {
const unsigned char *msg = (const unsigned char*)"Hello";
const unsigned char *key = (const unsigned char*)"Hello";
unsigned char out[32];
size_t outlen = 0;
hmac(msg, strlen(msg), key, strlen(key), out, &outlen, 32);
for (int i = 0; i < 32; i++) {
printf("%02x ", out[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment