五岁小站 - 免费在线工具箱

加载中...

HMAC 签名工具

HMAC 消息认证码 · 严格遵循 RFC 2104 / RFC 4231 标准 · 支持 9 种主流哈希算法 · 纯前端本地计算
当前: 0 字符
字符数: 0 | 字节数: 0
长度: 0 字符
典型场景模板
代码示例(HMAC-SHA256)
// Node.js 内置
const crypto = require('crypto');

const key  = 'mySecret';
const msg  = 'hello world';
const mac  = crypto.createHmac('sha256', key).update(msg, 'utf8').digest('hex');
// => 64 个 Hex 字符

// 浏览器 (Web Crypto)
async function hmacSha256(keyStr, msgStr) {
    const enc = new TextEncoder();
    const key = await crypto.subtle.importKey(
        'raw', enc.encode(keyStr),
        { name: 'HMAC', hash: 'SHA-256' },
        false, ['sign']);
    const sig = await crypto.subtle.sign('HMAC', key, enc.encode(msgStr));
    return [...new Uint8Array(sig)].map(b => b.toString(16).padStart(2,'0')).join('');
}
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public static String hmacSha256(String key, String msg) throws Exception {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    byte[] sig = mac.doFinal(msg.getBytes(StandardCharsets.UTF_8));
    StringBuilder sb = new StringBuilder();
    for (byte b : sig) sb.append(String.format("%02x", b));
    return sb.toString();
}
import hmac, hashlib

key = b'mySecret'
msg = b'hello world'
mac = hmac.new(key, msg, hashlib.sha256).hexdigest()
print(mac)

# 防止时序攻击的安全比较
hmac.compare_digest(mac1, mac2)
package main

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

func main() {
    h := hmac.New(sha256.New, []byte("mySecret"))
    h.Write([]byte("hello world"))
    fmt.Println(hex.EncodeToString(h.Sum(nil)))
}
<?php
$key = 'mySecret';
$msg = 'hello world';
$mac = hash_hmac('sha256', $msg, $key);            // hex
$macBin = hash_hmac('sha256', $msg, $key, true);   // binary
$macB64 = base64_encode($macBin);
echo $mac, PHP_EOL;
# 通过 OpenSSL
echo -n 'hello world' | openssl dgst -sha256 -hmac 'mySecret'

# Hex Key
KEY_HEX='6d795365637265744b6579'
echo -n 'hello world' | openssl dgst -sha256 -mac HMAC -macopt hexkey:$KEY_HEX

# 输出 Base64
echo -n 'hello' | openssl dgst -sha256 -hmac 'k' -binary | openssl base64
HMAC 算法说明
算法 输出长度 块大小 典型应用
HMAC-MD5128 位 / 16 字节64 字节RADIUS、TLS 1.0、CRAM-MD5(已不推荐)
HMAC-SHA1160 位 / 20 字节64 字节AWS S3 v2、OAuth 1.0、TLS 1.0/1.1(遗留)
HMAC-SHA224224 位 / 28 字节64 字节过渡用途
HMAC-SHA256256 位 / 32 字节64 字节JWT HS256、AWS V4、阿里云、GitHub、Stripe(首选)
HMAC-SHA384384 位 / 48 字节128 字节JWT HS384、TLS 1.3
HMAC-SHA512512 位 / 64 字节128 字节JWT HS512、BIP32 钱包派生、HKDF
HMAC-SHA3-256256 位136 字节新协议、抗 Keccak 攻击
HMAC-SHA3-512512 位72 字节新协议、最高安全级
HMAC-RIPEMD160160 位64 字节BTC 地址生成、欧洲银行
RFC 4231 标准测试向量(HMAC-SHA256 Test Case 1)
密钥 (Hex)0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
消息"Hi There" (UTF-8)
HMAC-SHA256b0344c61d8db38535ca8afceaf0bf12b 881dc200c9833da726e9376c2e32cff7