Sobes.tech
Middle

What is HMAC and how is it used?

sobes.tech AI

Answer from AI

HMAC (Hash-based Message Authentication Code) is a mechanism for verifying the integrity and authenticity of a message using a secret key and a cryptographic hash function.

Working algorithm:

  1. Formation of inner and outer keys from the secret key and constants (ipad, opad).
  2. Calculation of the inner hash: hash(secret key XOR ipad + message).
  3. Calculation of the outer hash: hash(secret key XOR opad + inner hash). This is the HMAC.

Usage:

  • API request authentication: The server and client share a secret key. The client computes the HMAC for the request data and sends it in the header. The server computes the HMAC for the same data and key, comparing it with the sent value. If they match, the request is considered authentic.
  • Data integrity verification: If the message's HMAC matches the re-computed HMAC, it can be assured that the data was not altered during transmission.
  • Usage in JSON Web Tokens (JWT): HMAC is often used as a digital signature algorithm (HS256, HS384, HS512) to ensure the integrity of token data.

Example implementation (pseudocode):

function hmacSHA256(key, message) {
    // padding constants
    const blockSize = 64; // for SHA-256
    const ipad = 0x36;
    const opad = 0x5c;

    // Prepare the key
    let paddedKey = key;
    if (key.length > blockSize) {
        paddedKey = sha256(key);
    }
    while (paddedKey.length < blockSize) {
        paddedKey += 0x00;
    }

    // Inner hash
    const innerPaddedKey = xor(paddedKey, ipad);
    const innerHash = sha256(innerPaddedKey + message);

    // Outer hash (HMAC)
    const outerPaddedKey = xor(paddedKey, opad);
    const hmac = sha256(outerPaddedKey + innerHash);

    return hmac;
}

// In real libraries, the implementation is optimized and differs

The key difference from simple hashing with key addition (hash(key + message) or hash(message + key)) is that HMAC is resistant to message extension attacks, as it uses two hashing phases with different padding constants.