← Lessons/Encoding, Hashing, HMAC & Encryption
← Encoding, Hashing, HMAC & Encryption

Authenticate with HMAC

Learn

HMAC: a hash only key holders can produce

To prove who produced the bytes, mix a secret key into the hash. HMAC (Hash-based Message Authentication Code) does this safely:

openssl dgst -sha256 -hmac "ops-shared-secret" config.txt
# HMAC-SHA2-256(config.txt)= bda22e…

Without the secret, nobody can compute the right tag for modified bytes. The receiver recomputes the HMAC with the same secret and compares the two. This is exactly what an HS256 JWT signature is (HMAC-SHA256 over the token), and it's how GitHub, Stripe and Slack sign their webhooks.

The limitation is that the key is symmetric. Anyone who can verify an HMAC can also create one. The next lesson fixes that with public/private key pairs.

Why not sha256(secret + message)? That naive construction is vulnerable to length-extension attacks on SHA-256. HMAC's nested design isn't. Always use HMAC.

A hash proves integrity but not who produced it. Compute the HMAC-SHA256 of config.txt with the shared secret ops-shared-secret and print it.

$ bash solution.sh
Loading...

Output

Run your solution to see its output here.