CodeBlanks Logo Icon CodeBlanks

HMAC

Learn message authentication with HMAC.

What is HMAC?

HMAC (Hash-based Message Authentication Code) produces a message authentication code using a hash with a key. The receiver computes the same code with the same key and compares; if equal, the message is unchanged and the sender is authentic.

In OpenSSL it is computed in a single call: HMAC(EVP_sha256(), key, keylen, data, datalen, digest, &len). key is the secret, data is the message. Unlike a plain hash, HMAC cannot be verified without the key; so it provides both integrity and authenticity. For testing, printing a fixed done message is enough.

The HMAC pattern

HMAC is computed in a single call: unsigned char digest[EVP_MAX_MD_SIZE]; unsigned int len = 0; HMAC(EVP_sha256(), "key", 3, (const unsigned char *)"msg", 3, digest, &len);. digest is the 32-byte authentication code.

The receiver computes the same code with the same key and message; compares with memcmp. If equal, the message is authentic. For testing, printf("hmac done\n") is enough; the code itself is environment-independent but printing byte values is complex. In production you show the code as hex.

Practice Compute HMAC

Declare unsigned char digest[EVP_MAX_MD_SIZE]; unsigned int len = 0;. Compute with HMAC(EVP_sha256(), "key", 3, (const unsigned char *)"msg", 3, digest, &len);. printf("hmac done\n");.

Starter code

main.c
#include <stdio.h>
#include <openssl/hmac.h>

// Compute HMAC
// Print done

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <openssl/hmac.h>

int main(void) {
    unsigned char digest[EVP_MAX_MD_SIZE];
    unsigned int len = 0;
    HMAC(EVP_sha256(), "key", 3, (const unsigned char *)"msg", 3, digest, &len);
    printf("hmac done\n");
    return 0;
}

Expected output

hmac done

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 HMAC call

Question
HMAC(____, "key", 3, (const unsigned char *)"msg", 3, digest, &len);
Answer
HMAC(EVP_sha256(), "key", 3, (const unsigned char *)"msg", 3, digest, &len);

Explanation: HMAC with EVP_sha256() does SHA-256 based authentication.

2 Match HMAC parts

Term Meaning
HMAC Auth code
key Secret
EVP_sha256 Hash algorithm
memcmp Compare

3 What is HMAC used for?

  • Message authentication Correct answer
  • Encryption
  • Compression
  • Random numbers

Explanation: HMAC is used for message authentication and integrity.

All lessons in Advanced