hash_hmac

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

用 HMAC(密钥哈希消息认证码)以指定算法计算带密钥的摘要。

C C23

C23
#include <stdio.h>
#include <string.h>
#include "sha256.h" // 随仓库入库的 SHA-256(Brad Conte,公有领域)

// 在 vendor SHA-256 之上实现 HMAC-SHA256(RFC 2104);假设密钥 <= 64 字节
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);

    // 校验:重算并比较(演示用 strcmp;真实代码应常数时间比较)
    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;
}
输出
10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7
true
false

C++ C++26

C++26
#include <cstdio>
#include <cstring>
#include "sha256.h" // 随仓库入库的 SHA-256(Brad Conte,公有领域)

// HMAC-SHA256(RFC 2104);假设密钥 <= 64 字节
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);

    // 校验:重算并比较
    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;
}
输出
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); // SHA-256 之上的 HMAC,.NET 标准库
string mac = Convert.ToHexString(hmac.ComputeHash(msg)).ToLowerInvariant();
Console.WriteLine(mac);

// 校验:重算并常数时间比较
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)));
输出
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")) // 通用接口:任何 hash.Hash 都可用
    mac.Write([]byte("payload"))
    fmt.Printf("%x\n", mac.Sum(nil))

    // 校验:重算并用 hmac.Equal 比较(常数时间)
    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)))
}
输出
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"); // 按算法名的通用工厂
        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));

        // 校验:重算并常数时间比较
        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); // 常数时间比较
    }
}
输出
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);

// 校验:重算并常数时间比较
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));
输出
10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7
true
false

PHP v8.6.0

v8.6.0
// HMAC = 带密钥的哈希:同一消息 + 同一密钥得到同一 MAC,密钥不同则 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')));
输出
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)

# 校验:重算并常数时间比较
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))
输出
10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7
True
False

Rust v1.99.1

v1.99.1
use sha2::{Digest, Sha256}; // sha2 crate(RustCrypto);此处无 hmac crate,按 RFC 2104 手写

// 在 sha2 crate 之上实现 HMAC-SHA256(RFC 2104);假设密钥 <= 64 字节
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));

    // 校验:重算并比较(演示用 ==;真实代码应常数时间比较)
    println!("{}", mac == hmac_sha256(b"secret-key", b"payload"));
    println!("{}", mac == hmac_sha256(b"wrong-key", b"payload"));
}
输出
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);

// 校验:重算并常数时间比较
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));
输出
10aa2e1c2538464ff75f0647271e3ba746bca3fcdeaf322c581bf5851e8cddb7
true
false

语言差异说明

C:标准库无 HMAC,vendor SHA-256 上按 RFC 2104 手写(ipad 0x36 / opad 0x5c 两轮哈希);比较演示用 strcmp,真实代码应常数时间比较。

C++:同 C,vendor SHA-256 上手写 RFC 2104。

C#:标准库 HMACSHA256;比较用常数时间函数 FixedTimeEquals。

Go:标准库 crypto/hmac + hmac.New(sha256.New, key)(通用 hash.Hash 接口,换算法只换构造参数);比较用 hmac.Equal(常数时间)。

Java:标准库 Mac.getInstance("HmacSHA256");比较用 MessageDigest.isEqual(常数时间)。

JavaScript:Node 标准库 crypto.createHmac;比较用 timingSafeEqual(常数时间)。

PHP:hash_hmac($algo, $data, $key) 一行出 MAC(RFC 2104,密钥过长时先压缩);MAC 与普通哈希的本质区别是「带密钥」——攻击者可改包并重算 md5/sha256,但没有密钥就造不出合法 MAC,因此 HMAC 兼具完整性+认证双重能力(Webhook 签名、API 请求签名、JWT HS256 都是它);比较验证必须用 hash_equals()(常数时间),直接 == 会在逐字节提前返回中泄露时序信息。

Python:标准库 hmac.new;比较用 hmac.compare_digest(常数时间)。

Rust:标准库无 HMAC,sha2 crate 上按 RFC 2104 手写(与 C/C++ 同构);真实项目用 hmac crate。

TypeScript:同 JS,Node createHmac 与 timingSafeEqual。