HMAC Generator

Generate and verify HMAC message authentication codes using various hash algorithms

Hash Algorithm

Output Format

Secret Key

The secret key is used to create the HMAC. Keep this key secure.

Error message
Copied!

HMAC Visualization

HMAC Computation Process

Key ⊕ ipad
Concatenate with message
Hash Function
Inner Hash
Key ⊕ opad
Concatenate with inner hash
Hash Function
HMAC Result

HMAC(K, m) = H((K' ⊕ opad) || H((K' ⊕ ipad) || m))

Where: K = Secret key K' = Derived key H = Hash function ⊕ = XOR operation || = Concatenation opad = Outer pad (0x5C...) ipad = Inner pad (0x36...)

Selected Algorithm Properties

Algorithm:
HMAC-SHA256
Security Strength:
Strong - Recommended for most security applications
Output Size:
256 bits (32 bytes / 64 hex characters)
Standards:
RFC 2104, FIPS 198-1

What is HMAC?

HMAC (Hash-based Message Authentication Code) is a specific type of message authentication code (MAC) that uses a cryptographic hash function along with a secret key to verify both the data integrity and authenticity of a message. It provides a way to check that data hasn't been tampered with and to verify that it came from the expected sender.

Key Benefits of HMAC

  • Data Integrity: Ensures the message hasn't been altered in transit
  • Authentication: Verifies the sender's identity if they possess the shared secret key
  • Simplicity: Builds on existing hash functions, making it easy to implement
  • Security: Resistant to various cryptographic attacks that plain hashes are vulnerable to

How HMAC Works

HMAC operates by combining a cryptographic hash function with a secret key. The process involves:

1. Key Derivation

If the secret key is longer than the hash function's block size, it is first hashed to produce a key of the appropriate length. If it's shorter than the block size, it's padded with zeros.

2. Inner Hash Computation

The derived key is XORed with a constant padding value called the inner pad (ipad, which is the byte 0x36 repeated to fill a block). This value is then concatenated with the message and hashed.

3. Outer Hash Computation

The derived key is XORed with a different constant padding value called the outer pad (opad, which is the byte 0x5C repeated to fill a block). This value is then concatenated with the result of the inner hash and hashed again.

4. Final HMAC Value

The result of the outer hash becomes the final HMAC value. This two-stage process helps protect against length extension attacks that plain hash functions are vulnerable to.

The formal definition of HMAC is:

HMAC(K, m) = H((K' ⊕ opad) || H((K' ⊕ ipad) || m))

Common HMAC Algorithms

HMAC Algorithm Output Size Security Status Recommended Use
HMAC-MD5 128 bits Weak (underlying hash is broken) Legacy systems only
HMAC-SHA1 160 bits Moderate (underlying hash has weaknesses) Legacy compatibility
HMAC-SHA256 256 bits Strong General purpose security
HMAC-SHA384 384 bits Very Strong Enhanced security applications
HMAC-SHA512 512 bits Very Strong High-security applications

Security Note on HMAC

Even though some underlying hash algorithms like MD5 and SHA-1 have known cryptographic weaknesses when used alone, HMAC construction provides additional security properties that can mitigate these weaknesses. For example, HMAC-MD5 and HMAC-SHA1 are not as vulnerable to collision attacks as the base hash functions.

However, for new applications, it's recommended to use HMAC with more secure hash functions like SHA-256 or SHA-512.

Applications of HMAC

HMAC is widely used in various security applications and protocols:

1. API Authentication

Many web APIs use HMAC for request authentication. The client includes an HMAC signature with each request, computed from the request details and a shared secret key. The server independently calculates the same signature and verifies it matches.

2. Message Authentication in TLS/SSL

Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer (SSL), use HMAC for message authentication during the encrypted communication process.

3. JSON Web Tokens (JWT)

JWTs often use HMAC algorithms (such as HS256, which is HMAC with SHA-256) to digitally sign the token payload, ensuring it hasn't been tampered with.

4. File Integrity Verification

HMAC can be used to verify that files haven't been altered, especially in situations where the verification needs to be authenticated (unlike a simple hash check).

5. Password Storage

While dedicated password hashing functions like bcrypt or Argon2 are preferred, HMAC can be part of a password hashing strategy when combined with appropriate salting and key stretching.

HMAC vs. Simple Hash Functions

While both HMAC and simple hash functions can verify data integrity, they serve different purposes:

Feature Simple Hash (e.g., SHA-256) HMAC (e.g., HMAC-SHA256)
Secret Key No Yes
Verifies Data Integrity Yes Yes
Verifies Data Source No Yes
Protection against Length Extension No (for many hash functions) Yes
Use Case Checksums, data integrity Authentication, secure messaging

HMAC Security Best Practices

To ensure the security of your HMAC implementations, follow these best practices:

1. Key Management

  • Use strong, random keys of sufficient length (at least as long as the hash function's output)
  • Keep keys secret and store them securely, not hardcoded in your application
  • Rotate keys periodically to limit the impact of potential compromises

2. Algorithm Selection

  • Choose secure hash functions like SHA-256 or SHA-512 for HMAC generation
  • Avoid deprecated hash functions like MD5 and SHA-1 for new applications
  • Consider the security requirements of your specific application

3. Implementation Considerations

  • Use constant-time comparison when verifying HMAC values to prevent timing attacks
  • Use established cryptographic libraries rather than implementing HMAC yourself
  • Include all security-relevant data in the message being authenticated
  • Include timestamps or nonces to prevent replay attacks

Common HMAC Implementation Mistakes

  • Using predictable keys or keys with insufficient entropy
  • Comparing HMAC values using regular string equality operators (vulnerable to timing attacks)
  • Reusing nonces or using predictable values in the message
  • Transmitting the key along with the HMAC (the key should never be shared in the same channel)
  • Not including all relevant context in the message being authenticated

HMAC vs. Other Authentication Methods

HMAC is one of several methods for ensuring data integrity and authenticity. Here's how it compares to some alternatives:

HMAC vs. Digital Signatures

  • Symmetric vs. Asymmetric: HMAC uses the same key for generation and verification, while digital signatures use a private key for signing and a public key for verification
  • Performance: HMAC is generally faster and less computationally intensive than digital signatures
  • Use Cases: Digital signatures are better for non-repudiation and scenarios involving multiple parties who shouldn't all be able to generate valid signatures

HMAC vs. Authenticated Encryption

  • Purpose: HMAC provides authentication and integrity but not confidentiality; authenticated encryption (like AES-GCM) provides all three
  • Implementation: Authenticated encryption is typically handled as a single operation, while HMAC requires separate encryption and authentication steps
  • Modern Recommendation: For most applications requiring both encryption and authentication, authenticated encryption modes are recommended

Code Examples for Different Languages

Here are examples of computing HMAC-SHA256 in various programming languages:

JavaScript

// Using the Web Crypto API
async function calculateHMAC(message, key) {
  // Convert to byte arrays
  const encoder = new TextEncoder();
  const messageData = encoder.encode(message);
  const keyData = encoder.encode(key);
  
  // Import the key
  const cryptoKey = await window.crypto.subtle.importKey(
    'raw', keyData, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
  );
  
  // Sign the message
  const signature = await window.crypto.subtle.sign(
    'HMAC', cryptoKey, messageData
  );
  
  // Convert signature to hex
  return Array.from(new Uint8Array(signature))
    .map(b => b.toString(16).padStart(2, '0'))
    .join('');
}

PHP

function calculateHMAC($message, $key) {
    return hash_hmac('sha256', $message, $key);
}

// Example
$hmac = calculateHMAC('Hello, world!', 'mysecretkey');
echo $hmac;

Python

import hmac
import hashlib

def calculate_hmac(message, key):
    return hmac.new(
        key.encode('utf-8'),
        message.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()

# Example
hmac_value = calculate_hmac('Hello, world!', 'mysecretkey')
print(hmac_value)

Conclusion

HMAC is a versatile and widely-used cryptographic primitive that provides authenticated integrity checking for messages. By combining the efficiency of hash functions with the security of a secret key, HMAC offers a robust mechanism for verifying that data hasn't been tampered with and comes from a trusted source.

For most modern applications, HMAC-SHA256 provides an excellent balance of security and performance. However, in contexts where the highest security is required, HMAC-SHA512 offers an even larger security margin. By following best practices in key management and implementation, HMAC can be a cornerstone of your application's security infrastructure.