👨‍💻
Application Security Handbook
  • Application Security Handbook
  • Web Application
    • Authentication
      • Authentication with Login and Password
      • Authentication with Phone Number
      • OAuth 2.0 Authentication
      • Multi-factor Authentication
      • Default Passwords
      • Password Change
      • Password Policy
      • Password Reset
      • Password Storage
      • One Time Password (OTP)
      • Email Address Confirmation
    • Authorization
    • Concept of Trusted Devices
    • Content Security Policy (CSP)
    • Cookie Security
    • Cryptography
      • Cryptographic Keys Management
      • Encryption
      • Hash-based Message Authentication Code (HMAC)
      • Hashing
      • Random Generators
      • Universal Unique Identifier (UUID)
    • Error and Exception Handling
    • File Upload
    • Input Validation
    • JSON Web Token (JWT)
    • Logging and Monitoring
    • Output Encoding
    • Regular Expressions
    • Sensitive Data Management
    • Session Management
    • Transport Layer Protection
    • Vulnerability Mitigation
      • Brute-force
      • Command Injection
      • Cross-Site Request Forgery (CSRF)
      • Cross-Site Scripting (XSS)
      • Mass Parameter Assignment
      • Parameter Pollution
      • Path Traversal
      • Regular Expression Denial of Service (ReDoS)
      • SQL Injection (SQLi)
      • XML External Entity (XXE) Injection
Powered by GitBook
On this page
  • Overview
  • General
  • HMAC implementation
  1. Web Application
  2. Cryptography

Hash-based Message Authentication Code (HMAC)

PreviousEncryptionNextHashing

Last updated 1 year ago

Overview

This page contains recommendations for using a Hash-based message authentication code (HMAC).

General

  • Use secret keys of length 16+ bytes.

  • The length of a secret key does not exceed a hash block size.

Hash algorithm
Block size, bytes

SHA-256

64

SHA-512

128

SHA3-256

136

SHA3-512

72

  • You can use HMAC to check the integrity (signature) of messages between internal systems.

  • Do not use HMAC to integrate with a third-party system, use digital signatures.

  • Use HMAC based on hash algorithms from the SHA-2 family.

HMAC implementation

import (
    "crypto/sha256"
    "crypto/hmac"
)

func CalculateHMAC(message, key []byte) []bytes {
    mac := hmac.New(sha256.New, key)
    mac.Write(message)
    return mac.Sum(nil)
}
import javax.crypto.Mac;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;

public static byte[] calculateHMAC(String message, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
    Mac hasher = Mac.getInstance("HmacSHA256");
	hasher.init(new SecretKeySpec(key, "HmacSHA256"));
    return hasher.doFinal(message.getBytes());
}
const { createHmac } = await import('node:crypto');

async function calculateHMAC(message, key) {
    const hmac = createHmac('sha256', key);
    hmac.update(message);
    return hmac.digest('hex');
}
import hmac

def calculate_hmac(message: str, key: bytes | bytearray):
    h = hmac.new(key, message, hashlib.sha256)
    return h.hexdigest()

def compare_hmac_digests(a: str | bytes, b: str | bytes) -> bool:
    return hmac.compare_digest(a, b)

Comply with requirements from the page when choosing a hash algorithm.

Comply with requirements from the page when generating and storing a secret key.

Use the package to calculate HMAC in Go.

Use the class to calculate HMAC. You can find supported Mac algorithms at .

Use the package to calculate HMAC.

Use the package to calculate HMAC. Use function instead of the == operator to compare digests. Using reduces the vulnerability to timing attacks.

Cryptography: Hashing
Cryptography: Cryptographic Keys Management
crypto/hmac
javax.crypto.Mac
Java Security Standard Algorithm Names: Mac Algorithms
crypto
hmac
hmac.compare_digest
hmac.compare_digest