20 # include <openssl/evp.h>
21 # if !CFG_USE_OPENSSL_API_3
22 # include <openssl/hmac.h>
48 #define MAIN_ERR_PREFIX "HMAC: "
64 static int hmac_openssl(
enum hmac_alg alg,
const char* text,
65 size_t text_len,
const char* key,
size_t key_len,
70 # if CFG_USE_OPENSSL_API_3
71 EVP_MAC* evp_mac = NULL;
72 EVP_MAC_CTX* ctx = NULL;
79 const EVP_MD* hmac_id = NULL;
80 unsigned int mac_len = 0;
82 size_t mac_len_check = 1;
88 case HMAC_ALG_SHA1_160:
90 # if CFG_USE_OPENSSL_API_3
99 case HMAC_ALG_SHA2_256:
101 # if CFG_USE_OPENSSL_API_3
104 hmac_id = EVP_sha256();
121 # if CFG_USE_OPENSSL_API_3
122 evp_mac = EVP_MAC_fetch(NULL,
"HMAC", NULL);
125 ctx = EVP_MAC_CTX_new(evp_mac);
128 # elif CFG_USE_OPENSSL_API_1_1 || CFG_USE_LIBRESSL_API_3_5
129 ctx = HMAC_CTX_new();
131 ctx = (HMAC_CTX*) posix_malloc(
sizeof(HMAC_CTX));
133 if(NULL == ctx) {
PRINT_ERROR(
"Creating context failed"); }
136 else if(!(POSIX_INT_MAX >= text_len && POSIX_INT_MAX >= key_len))
143 # if CFG_USE_OPENSSL_API_3
144 params[0] = OSSL_PARAM_construct_utf8_string(
"digest",
146 params[1] = OSSL_PARAM_construct_end();
147 rv = EVP_MAC_init(ctx, (
const unsigned char*) key, key_len, params);
154 rv = EVP_MAC_update(ctx, (
const unsigned char*) text, text_len);
157 rv = EVP_MAC_final(ctx, mac, &mac_len, mac_len_check);
163 else if(NULL != mac && mac_len_check == (
size_t) mac_len)
169 # if CFG_USE_OPENSSL_API_1_1 || CFG_USE_LIBRESSL_API_3_5
175 mac = HMAC(hmac_id, (
void*) key, (
int) key_len, (
unsigned char*) text,
176 text_len, (
unsigned char*) mac, &mac_len);
177 if(NULL != mac && mac_len_check == (
size_t) mac_len) { res = 0; }
185 # if CFG_USE_OPENSSL_API_3
186 EVP_MAC_CTX_free(ctx);
187 # elif CFG_USE_OPENSSL_API_1_1 || CFG_USE_LIBRESSL_API_3_5
190 HMAC_CTX_cleanup(ctx);
191 posix_free((
void*) ctx);
195 # if CFG_USE_OPENSSL_API_3
197 EVP_MAC_free(evp_mac);
225 const char* key,
size_t key_len,
unsigned char* mac)
227 return(hmac_openssl(HMAC_ALG_SHA1_160, text, text_len, key, key_len, mac));
251 const char* key,
size_t key_len,
unsigned char* mac)
253 return(hmac_openssl(HMAC_ALG_SHA2_256, text, text_len, key, key_len, mac));