What is HMAC?
sobes.tech AI
Answer from AI
HMAC (Hash-based Message Authentication Code) is a mechanism for verifying the integrity and authenticity of a message. It uses a cryptographic hash function (e.g., SHA-256) and a secret key.
Working principle:
- The secret key is combined with the message.
- The result is hashed.
- The secret key is combined again with the previous hash result.
- The final result is hashed once more.
The resulting HMAC value is attached to the message. The receiver, having the same secret key, can compute the HMAC for the received message and compare it with the attached value. If they match, the message has not been altered and was created by the sender with the same key.
// Example of using HMAC-SHA256 in Node.js
const crypto = require('crypto');
const secret = 'your-secret-key';
const message = 'message text for authenticity check';
const hmac = crypto.createHmac('sha256', secret);
hmac.update(message);
const hmacValue = hmac.digest('hex');
// console.log(hmacValue); // Outputs the HMAC value in hexadecimal format
Advantages:
- Ensures both integrity and authenticity.
- Uses standard hash functions.
- Resistant to various cryptographic attacks when used correctly.
Differences from simple hash functions: A simple hash function (e.g., SHA-256) only guarantees data integrity but not authenticity. An attacker can modify the message and compute a new hash for it, remaining unnoticed. HMAC, using a secret key, prevents this. Only someone who knows the key can compute the correct HMAC value for the message.