Hash-based Message Authentication Code (HMAC)
Overview
This page contains recommendations for using a Hash-based message authentication code (HMAC).
General
Comply with requirements from the Cryptography: Hashing page when choosing a hash algorithm.
Comply with requirements from the Cryptography: Cryptographic Keys Management page when generating and storing a secret key.
Use secret keys of length 16+ bytes.
The length of a secret key does not exceed a hash block size.
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-2family.
HMAC implementation
Use the crypto/hmac package to calculate HMAC in Go.
import (
"crypto/sha256"
"crypto/hmac"
)
func CalculateHMAC(message, key []byte) []bytes {
mac := hmac.New(sha256.New, key)
mac.Write(message)
return mac.Sum(nil)
}Use the javax.crypto.Mac class to calculate HMAC. You can find supported Mac algorithms at Java Security Standard Algorithm Names: Mac Algorithms.
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());
}Use the crypto package to calculate HMAC.
const { createHmac } = await import('node:crypto');
async function calculateHMAC(message, key) {
const hmac = createHmac('sha256', key);
hmac.update(message);
return hmac.digest('hex');
}Use the hmac package to calculate HMAC. Use hmac.compare_digest function instead of the == operator to compare digests. Using hmac.compare_digest reduces the vulnerability to timing attacks.
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)Last updated