HMAC 生成器
使用 SHA-256/384/512 生成 HMAC 签名。
关于此工具
HMAC(哈希消息身份验证码)是一种密码学技术,用于验证传输或存储中数据的完整性和真实性。通过将秘密密钥与消息结合,HMAC会生成一个唯一的签名,证明数据未被篡改,且只有持有秘密密钥的人才能生成它。这使其对于保护API、验证Webhook、签署凭证以及保护互联网上的敏感通信至关重要。
要使用此工具,请在文本字段中输入您的消息,并提供与接收者共享的秘密密钥。根据您的安全需求选择哈希算法(SHA-256、SHA-384或SHA-512),然后单击"生成HMAC"以生成签名。生成的哈希可以与数据一起发送,接收者可以使用他们的秘密密钥副本生成相同的HMAC来验证真实性。
HMAC广泛用于支付处理器、云API(AWS、Google Cloud、Stripe)和实时通信系统,以防止篡改并确认消息来源。SHA-256变体为大多数用例提供了强大的安全性,而SHA-384和SHA-512为高度敏感的应用提供了额外的安全保证。请记住,HMAC的安全性完全取决于保持秘密密钥的私密性——切勿通过不安全的渠道共享它。
常见问题
代码实现
import hmac
import hashlib
import base64
import secrets
# Generate HMAC-SHA256
key = secrets.token_bytes(32) # 256-bit random key
message = "Hello, World!"
# Raw hex output
mac = hmac.new(key, message.encode(), hashlib.sha256)
print("HMAC-SHA256 (hex):", mac.hexdigest())
# Base64 output (common for API signatures)
mac_b64 = base64.b64encode(mac.digest()).decode()
print("HMAC-SHA256 (b64):", mac_b64)
# HMAC-SHA512
mac512 = hmac.new(key, message.encode(), hashlib.sha512)
print("HMAC-SHA512 (hex):", mac512.hexdigest())
# Constant-time verification (prevents timing attacks)
def verify_hmac(key: bytes, message: str, expected: str) -> bool:
computed = hmac.new(key, message.encode(), hashlib.sha256).hexdigest()
return hmac.compare_digest(computed, expected)
signature = mac.hexdigest()
print("Valid: ", verify_hmac(key, message, signature)) # True
print("Invalid:", verify_hmac(key, "tampered", signature)) # FalseComments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.