import base64 import hashlib import hmac import time def _normalize_bytes(value: str | bytes) -> bytes: return value.encode("utf-8") if isinstance(value, str) else value def hmac_sha256_sign(secret: str | bytes, message: str | bytes) -> bytes: """使用 HMAC-SHA256 对消息进行签名,返回原始字节签名。""" key = _normalize_bytes(secret) msg = _normalize_bytes(message) return hmac.new(key, msg, hashlib.sha256).digest() def hmac_sha256_base64(secret: str | bytes, message: str | bytes) -> str: """使用 HMAC-SHA256 对消息进行签名,返回 Base64 编码字符串。""" return base64.b64encode(hmac_sha256_sign(secret, message)).decode("utf-8") def verify_hmac_digest(secret: str | bytes, message: str | bytes, signature: str | bytes | None) -> bool: """验证 HMAC-SHA256 签名是否匹配。""" if signature is None: return False expected = hmac_sha256_sign(secret, message) actual = _normalize_bytes(signature) return hmac.compare_digest(expected, actual) def sha1_sorted_sign(*parts: str) -> str: """将多个字符串排序拼接后进行 SHA1 签名,返回十六进制字符串。""" return hashlib.sha1("".join(sorted(parts)).encode("utf-8")).hexdigest() def verify_timestamp(timestamp: str | int, tolerance: int = 300) -> bool: """校验时间戳与当前时间的偏差是否在允许范围内。""" try: ts = int(timestamp) except (TypeError, ValueError): return False return abs(int(time.time()) - ts) <= tolerance