Sobes.tech
Middle+

What is HMAC?

sobes.tech AI

Answer from AI

HMAC (Keyed-Hash Message Authentication Code) is a mechanism for verifying the integrity and authenticity of a message using a cryptographic hash function and a secret key. It guarantees that the message has not been tampered with and originates from a trusted sender.

Working principle:

  1. Take the message.
  2. The secret key is padded or truncated to match the block size of the hash function.
  3. The result is XORed with the constant ipad (inner pad).
  4. The message is combined with this result and processed through the hash function.
  5. The secret key is XORed with the constant opad (outer pad).
  6. The result of the previous hash is combined with this result and processed again through the hash function.
  7. The result of the second hash is the HMAC.

On the sender's side, the HMAC for the message is computed using the secret key and sent along with the message.

On the receiver's side, the HMAC for the received message is computed using the same secret key. The computed HMAC is compared with the one sent. If they match, the message is considered authentic and unaltered.

HMAC is resistant to length-extension attacks, which can affect simple schemes like hash(key + message) or hash(message + key).

Examples of usage:

  • Authentication of messages in network protocols (e.g., IPsec, TLS/SSL).
  • Data integrity verification.
  • Creating JSON Web Tokens (JWT).
// Example in Node.js using the built-in 'crypto' module
const crypto = require('crypto');

const secretKey = 'my-secret-key';
const message = 'This is the message to authenticate.';

// Create an HMAC object with SHA256 algorithm and the key
const hmac = crypto.createHmac('sha256', secretKey);

// Update the HMAC with the message data
hmac.update(message);

// Get the digest (HMAC) in hexadecimal format
const hmacDigest = hmac.digest('hex');

console.log(hmacDigest); // Outputs the HMAC for the message