API 鉴权签名计算引擎(专业版)
输入
body_digest(body);build_sign_string(method,path,ts,nonce,body);hmac_sha256_sign(secret,s);verify_signature(secret,s,sig);auth_header(scheme,key,secret,method,path,ts,nonce,body);is_jwt_expired(exp,now,leeway=0)
输出
体摘要hex;规范签名串;64位hex签名;校验bool;Authorization头;过期bool
硬性规则
- 签名串五段以 \n 连接,方法统一大写,体摘要为 SHA256。
- 验签用 hmac.compare_digest 恒定时间比较。
- now>exp+leeway 才过期;exp=None 返回 False。
示例
hmac_sha256_sign("k", build_sign_string("get","/x",1,"n","")) → 64位hex,重算一致
verify_signature("k",s, 正确签名) → True;错误secret → False
is_jwt_expired(1000, now=1000, leeway=0) → False(恰好到期时刻不过期)
Python 引擎(可独立运行)
# -*- coding: utf-8 -*-
import hmac, hashlib, time
def body_digest(body=""):
"""请求体 SHA256 摘要,空体也参与签名防篡改。"""
return hashlib.sha256((body or "").encode("utf-8")).hexdigest()
def build_sign_string(method, path, timestamp, nonce, body=""):
"""规范签名串:方法(大写)\n路径\n时间戳\n随机串\n请求体摘要。"""
return "\n".join([method.upper(), path, str(timestamp), str(nonce), body_digest(body)])
def hmac_sha256_sign(secret, sign_string):
"""HMAC-SHA256 十六进制签名(64位hex)。"""
return hmac.new(secret.encode("utf-8"), sign_string.encode("utf-8"),
hashlib.sha256).hexdigest()
def verify_signature(secret, sign_string, signature):
"""恒定时间比较,防时序侧信道;签名不匹配返回 False。"""
return hmac.compare_digest(hmac_sha256_sign(secret, sign_string), signature or "")
def auth_header(scheme, key, secret, method, path, timestamp, nonce, body=""):
"""生成 Authorization 头。scheme: 'Bearer' 或 'HMAC'。"""
if scheme.upper() == "BEARER":
return f"Bearer {key}"
sig = hmac_sha256_sign(secret, build_sign_string(method, path, timestamp, nonce, body))
return f'HMAC-SHA256 key="{key}",ts="{timestamp}",nonce="{nonce}",sig="{sig}"'
def is_jwt_expired(exp, now=None, leeway=0):
"""JWT 是否过期。exp 为过期时间戳(秒);无 exp 按 RFC7519 视为不过期;
leeway 为时钟偏移容差秒;now>exp+leeway 才判过期。"""
if exp is None:
return False
if now is None:
now = int(time.time())
return now > exp + leeway