hash_hmac

hash_hmac(string $algo, string $data, string $key, bool $binary = false): string

Computes a keyed digest of a message with HMAC (Hash-based Message Authentication Code) using the given algorithm.

C C23

C23
#include <stdio.h>
#include <string.h>
#include "sha256.h" // vendored SHA-256 (Brad Conte, public domain)

// HMAC-SHA256 (RFC 2104) on top of the vendored SHA-256; key <= 64 bytes assumed
static void hmac_sha256(const BYTE *key, size_t keylen, const BYTE *msg, size_t msglen, BYTE out[32]) {
    BYTE k[64] = {0}, ipad[64], opad[64], inner[32];
    SHA256_CTX ctx;
    memcpy(k, key, keylen);
    for (int i = 0; i < 64; i++) {
        ipad[i] = k[i] ^ 0x36;
        opad[i] = k[i] ^ 0x5c;
    }
    sha256_init(&ctx);
    sha256_update(&ctx, ipad, 64);
    sha256_update(&ctx, msg, msglen);
    sha256_final(&ctx, inner);
    sha256_init(&ctx);
    sha256_update(&ctx, opad, 64);
    sha256_update(&ctx, inner, 32);
    sha256_final(&ctx, out);
}

int main(void) {
    const char *key = "secret-key", *msg = "payload";
    BYTE mac[32];
    char hex[65] = {0};
    hmac_sha256((const BYTE *)key, strlen(key), (const BYTE *)msg, strlen(msg), mac);
    for (int i = 0; i < 32; i++) sprintf(hex + i * 2, "%02x", mac[i]);
    printf("%s\n", hex);

    // verify: recompute and compare (demo uses strcmp; real code compares constant-time)
    BYTE mac2[32];
    char hex2[65] = {0};
    hmac_sha256((const BYTE *)key, strlen(key), (const BYTE *)msg, strlen(msg), mac2);
    for (int i = 0; i < 32; i++) sprintf(hex2 + i * 2, "%02x", mac2[i]);
    printf("%s\n", strcmp(hex, hex2) == 0 ? "true" : "false");
    hmac_sha256((const BYTE *)"wrong-key", 9, (const BYTE *)msg, strlen(msg), mac2);
    for (int i = 0; i < 32; i++) sprintf(hex2 + i * 2, "%02x", mac2[i]);
    printf("%s\n", strcmp(hex, hex2) == 0 ? "true" : "false");
    return 0;
}
Output
10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7
true
false

C++ C++26

C++26
#include <cstdio>
#include <cstring>
#include "sha256.h" // vendored SHA-256 (Brad Conte, public domain)

// HMAC-SHA256 (RFC 2104); key <= 64 bytes assumed
static void hmac_sha256(const BYTE *key, size_t keylen, const BYTE *msg, size_t msglen, BYTE out[32]) {
    BYTE k[64] = {0}, ipad[64], opad[64], inner[32];
    SHA256_CTX ctx;
    memcpy(k, key, keylen);
    for (int i = 0; i < 64; i++) {
        ipad[i] = k[i] ^ 0x36;
        opad[i] = k[i] ^ 0x5c;
    }
    sha256_init(&ctx);
    sha256_update(&ctx, ipad, 64);
    sha256_update(&ctx, msg, msglen);
    sha256_final(&ctx, inner);
    sha256_init(&ctx);
    sha256_update(&ctx, opad, 64);
    sha256_update(&ctx, inner, 32);
    sha256_final(&ctx, out);
}

static void to_hex(const BYTE mac[32], char hex[65]) {
    for (int i = 0; i < 32; i++) sprintf(hex + i * 2, "%02x", mac[i]);
    hex[64] = 0;
}

int main() {
    const char *key = "secret-key", *msg = "payload";
    BYTE mac[32];
    char hex[65] = {0};
    hmac_sha256((const BYTE *)key, strlen(key), (const BYTE *)msg, strlen(msg), mac);
    to_hex(mac, hex);
    printf("%s\n", hex);

    // verify: recompute and compare
    BYTE mac2[32];
    char hex2[65] = {0};
    hmac_sha256((const BYTE *)key, strlen(key), (const BYTE *)msg, strlen(msg), mac2);
    to_hex(mac2, hex2);
    printf("%s\n", strcmp(hex, hex2) == 0 ? "true" : "false");
    hmac_sha256((const BYTE *)"wrong-key", 9, (const BYTE *)msg, strlen(msg), mac2);
    to_hex(mac2, hex2);
    printf("%s\n", strcmp(hex, hex2) == 0 ? "true" : "false");
    return 0;
}
Output
10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7
true
false

C# v11.0.100

v11.0.100
using System.Security.Cryptography;
using System.Text;

byte[] key = Encoding.UTF8.GetBytes("secret-key");
byte[] msg = Encoding.UTF8.GetBytes("payload");

using var hmac = new HMACSHA256(key); // HMAC over SHA-256, standard in .NET
string mac = Convert.ToHexString(hmac.ComputeHash(msg)).ToLowerInvariant();
Console.WriteLine(mac);

// verify: recompute and compare constant-time
using var hmac2 = new HMACSHA256(key);
bool ok = CryptographicOperations.FixedTimeEquals(hmac.ComputeHash(msg), hmac2.ComputeHash(msg));
Console.WriteLine(ok);
using var hmac3 = new HMACSHA256(Encoding.UTF8.GetBytes("wrong-key"));
Console.WriteLine(CryptographicOperations.FixedTimeEquals(hmac.ComputeHash(msg), hmac3.ComputeHash(msg)));
Output
10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7
True
False

Go v1.27.4

v1.27.4
package main

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

func main() {
    mac := hmac.New(sha256.New, []byte("secret-key")) // generic: any hash.Hash works
    mac.Write([]byte("payload"))
    fmt.Printf("%x\n", mac.Sum(nil))

    // verify: recompute and compare with hmac.Equal (constant-time)
    mac2 := hmac.New(sha256.New, []byte("secret-key"))
    mac2.Write([]byte("payload"))
    fmt.Println(hmac.Equal(mac.Sum(nil), mac2.Sum(nil)))
    mac3 := hmac.New(sha256.New, []byte("wrong-key"))
    mac3.Write([]byte("payload"))
    fmt.Println(hmac.Equal(mac.Sum(nil), mac3.Sum(nil)))
}
Output
10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7
true
false

Java v27.0.1

v27.0.1
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    public static void main(String[] args) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256"); // generic factory by algorithm name
        mac.init(new SecretKeySpec("secret-key".getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] digest = mac.doFinal("payload".getBytes(StandardCharsets.UTF_8));
        System.out.println(HexFormat.of().formatHex(digest));

        // verify: recompute and compare constant-time
        System.out.println(constantTimeEqual(digest, compute("secret-key")));
        System.out.println(constantTimeEqual(digest, compute("wrong-key")));
    }

    static byte[] compute(String key) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        return mac.doFinal("payload".getBytes(StandardCharsets.UTF_8));
    }

    static boolean constantTimeEqual(byte[] a, byte[] b) throws Exception {
        return MessageDigest.isEqual(a, b); // constant-time compare
    }
}
Output
10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7
true
false

JavaScript v26.13.1

v26.13.1
const { createHmac, timingSafeEqual } = require("node:crypto");

const mac = createHmac("sha256", "secret-key").update("payload").digest("hex");
console.log(mac);

// verify: recompute and compare constant-time
const again = createHmac("sha256", "secret-key").update("payload").digest();
const original = Buffer.from(mac, "hex");
console.log(timingSafeEqual(original, again));
const wrong = createHmac("sha256", "wrong-key").update("payload").digest();
console.log(timingSafeEqual(original, wrong));
Output
10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7
true
false

PHP v8.6.0

v8.6.0
// HMAC = a keyed hash: same message + same key -> same MAC, different key -> different MAC
echo hash_hmac('sha256', 'payload', 'secret-key'), "\n";
var_dump(hash_equals(hash_hmac('sha256', 'payload', 'secret-key'), hash_hmac('sha256', 'payload', 'secret-key')));
var_dump(hash_equals(hash_hmac('sha256', 'payload', 'secret-key'), hash_hmac('sha256', 'payload', 'wrong-key')));
Output
10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7
bool(true)
bool(false)

Python v3.15.2

v3.15.2
import hashlib
import hmac

mac = hmac.new(b"secret-key", b"payload", hashlib.sha256).hexdigest()
print(mac)

# verify: recompute and compare constant-time
again = hmac.new(b"secret-key", b"payload", hashlib.sha256).digest()
original = bytes.fromhex(mac)
print(hmac.compare_digest(original, again))
wrong = hmac.new(b"wrong-key", b"payload", hashlib.sha256).digest()
print(hmac.compare_digest(original, wrong))
Output
10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7
True
False

Rust v1.99.1

v1.99.1
use sha2::{Digest, Sha256}; // sha2 crate (RustCrypto); no hmac crate here, RFC 2104 hand-written

// HMAC-SHA256 (RFC 2104) on top of the sha2 crate; key <= 64 bytes assumed
fn hmac_sha256(key: &[u8], msg: &[u8]) -> [u8; 32] {
    let mut k = [0u8; 64];
    k[..key.len()].copy_from_slice(key);
    let mut ipad = [0x36u8; 64];
    let mut opad = [0x5cu8; 64];
    for i in 0..64 {
        ipad[i] ^= k[i];
        opad[i] ^= k[i];
    }
    let mut inner = Sha256::new();
    inner.update(ipad);
    inner.update(msg);
    let inner = inner.finalize();
    let mut outer = Sha256::new();
    outer.update(opad);
    outer.update(inner);
    outer.finalize().into()
}

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{:02x}", b)).collect()
}

fn main() {
    let mac = hmac_sha256(b"secret-key", b"payload");
    println!("{}", hex(&mac));

    // verify: recompute and compare (demo uses ==; real code compares constant-time)
    println!("{}", mac == hmac_sha256(b"secret-key", b"payload"));
    println!("{}", mac == hmac_sha256(b"wrong-key", b"payload"));
}
Output
10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7
true
false

TypeScript v26.13.1

v26.13.1
import { createHmac, timingSafeEqual } from "node:crypto";

const mac: string = createHmac("sha256", "secret-key").update("payload").digest("hex");
console.log(mac);

// verify: recompute and compare constant-time
const again: Buffer = createHmac("sha256", "secret-key").update("payload").digest();
const original: Buffer = Buffer.from(mac, "hex");
console.log(timingSafeEqual(original, again));
const wrong: Buffer = createHmac("sha256", "wrong-key").update("payload").digest();
console.log(timingSafeEqual(original, wrong));
Output
10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7
true
false

Language differences

C: no built-in HMAC — hand-written RFC 2104 (ipad 0x36 / opad 0x5c, two hash passes) on the vendored SHA-256; demo compares with strcmp, real code should compare constant-time.

C++: same as C, hand-written RFC 2104 on the vendored SHA-256.

C#: standard-library HMACSHA256; comparison uses the constant-time FixedTimeEquals.

Go: standard library crypto/hmac with hmac.New(sha256.New, key) (generic hash.Hash interface — swap the algorithm by swapping the constructor argument); comparison uses hmac.Equal (constant-time).

Java: standard library Mac.getInstance("HmacSHA256"); comparison uses MessageDigest.isEqual (constant-time).

JavaScript: Node standard library crypto.createHmac; comparison uses timingSafeEqual (constant-time).

PHP: hash_hmac($algo, $data, $key) produces the MAC in one call (RFC 2104, over-long keys are compressed first); the essential difference from a plain hash is the key — an attacker can tamper and recompute md5/sha256, but cannot forge a valid MAC without the key, so HMAC provides integrity plus authenticity (webhook signatures, API request signing, JWT HS256 all use it); verification must compare with hash_equals() (constant time) — plain == leaks timing through early byte-wise returns.

Python: standard library hmac.new; comparison uses hmac.compare_digest (constant time).

Rust: no built-in HMAC — hand-written RFC 2104 on the sha2 crate (same structure as C/C++); real projects use the hmac crate.

TypeScript: same as JS — Node createHmac with timingSafeEqual.