签名算法
KyrenPay使用 HMAC-SHA256 对 Webhook 载荷进行签名:signature = "sha256=" + HMAC-SHA256(timestamp + "." + payload, webhook_secret)
| 请求头 | 示例 |
|---|---|
X-Kyren-Signature | sha256=5d2dc4f1a... |
X-Kyren-Timestamp | 1704628800000(Unix 毫秒时间戳) |
验证步骤
1
提取请求头
从请求头中读取
X-Kyren-Signature 和 X-Kyren-Timestamp。2
检查时间戳
验证时间戳在当前时间的 5 分钟(300000 毫秒)以内。这可以防止重放攻击。
3
计算期望签名
拼接
timestamp + "." + 原始请求体,然后使用你的 Webhook 密钥计算 HMAC-SHA256。4
比较签名
将计算出的签名与请求头中的签名进行比较。使用常量时间比较以防止时序攻击。
代码示例
原始 Webhook 路由必须先于全局 JSON 解析器注册,或只在普通业务路由解析 JSON。解析事件前先校验请求头并使用原始请求体验签。下列示例需实现自己的持久化通知适配器:按唯一事件 ID 保存待处理通知后才返回2xx,工作进程负责重试和幂等履约。异常请求头应拒绝,而不是抛出未处理异常。每次投递重试都会生成新的发送时间戳,验签使用请求头时间戳,不使用 created_at。
Node.js
const crypto = require('crypto');
function verifyWebhookSignature(payload, signature, timestamp, secret) {
if (typeof secret !== 'string' || !secret) return false;
if (typeof signature !== 'string' || !/^sha256=[0-9a-f]{64}$/.test(signature)) return false;
if (typeof timestamp !== 'string' || !/^\d+$/.test(timestamp)) return false;
const sentAt = Number(timestamp);
if (!Number.isSafeInteger(sentAt) || Math.abs(Date.now() - sentAt) > 300000) return false;
const data = `${timestamp}.${payload}`;
const expected = 'sha256=' + crypto
.createHmac('sha256', secret)
.update(data)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(expected),
Buffer.from(signature)
);
}
app.post('/webhooks/kyren',
express.raw({ type: 'application/json' }),
async (req, res) => {
const signature = req.headers['x-kyren-signature'];
const timestamp = req.headers['x-kyren-timestamp'];
if (!Buffer.isBuffer(req.body)) return res.status(400).send('Raw JSON body required');
const payload = req.body.toString('utf8');
if (!verifyWebhookSignature(payload, signature, timestamp, process.env.KYREN_WEBHOOK_SECRET)) {
return res.status(400).send('Invalid signature');
}
let event;
try { event = JSON.parse(payload); } catch { return res.status(400).send('Invalid JSON'); }
if (!event || typeof event.id !== 'string' || !event.id || typeof event.type !== 'string' || !event.data) {
return res.status(400).send('Invalid event');
}
try {
await webhookInbox.insertIfAbsent(event.id, event);
} catch {
return res.status(503).send('Retry later');
}
res.status(200).send('OK');
}
);
Python
import hmac
import hashlib
import time
import re
def verify_webhook_signature(payload: str, signature: str, timestamp: str, secret: str) -> bool:
# 检查时间戳容差(5 分钟)
if not isinstance(secret, str) or not secret:
return False
if not isinstance(signature, str) or not re.fullmatch(r"sha256=[0-9a-f]{64}", signature):
return False
if not isinstance(timestamp, str) or not re.fullmatch(r"[0-9]{1,16}", timestamp):
return False
if int(timestamp) > 9007199254740991:
return False
current_time = int(time.time() * 1000)
if abs(current_time - int(timestamp)) > 300000:
return False
# 计算期望签名
data = f"{timestamp}.{payload}"
expected = "sha256=" + hmac.new(
secret.encode("utf-8"),
data.encode("utf-8"),
hashlib.sha256
).hexdigest()
# 常量时间比较
return hmac.compare_digest(expected, signature)
# 在 Flask 中使用
from flask import Flask, request
app = Flask(__name__)
@app.route("/webhooks/kyren", methods=["POST"])
def webhook():
payload = request.get_data(as_text=True)
signature = request.headers.get("X-Kyren-Signature", "")
timestamp = request.headers.get("X-Kyren-Timestamp", "")
if not verify_webhook_signature(payload, signature, timestamp, WEBHOOK_SECRET):
return "Invalid signature", 400
event = request.get_json()
if not isinstance(event, dict) or not isinstance(event.get("id"), str) or not event["id"]:
return "Invalid event", 400
try:
webhook_inbox.insert_if_absent(event["id"], event)
except Exception:
return "Retry later", 503
return "OK", 200
Go
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"encoding/json"
"math"
"net/http"
"strconv"
"regexp"
"time"
)
func verifyWebhookSignature(payload, signature, timestamp, secret string) bool {
if secret == "" || !regexp.MustCompile("^sha256=[0-9a-f]{64}$").MatchString(signature) ||
!regexp.MustCompile("^[0-9]+$").MatchString(timestamp) {
return false
}
// 检查时间戳容差(5 分钟)
ts, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil || ts > 9007199254740991 {
return false
}
currentTime := time.Now().UnixMilli()
if math.Abs(float64(currentTime-ts)) > 300000 {
return false
}
// 计算期望签名
data := fmt.Sprintf("%s.%s", timestamp, payload)
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(data))
expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
// 常量时间比较
return hmac.Equal([]byte(expected), []byte(signature))
}
func webhookHandler(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Invalid body", http.StatusBadRequest)
return
}
payload := string(body)
signature := r.Header.Get("X-Kyren-Signature")
timestamp := r.Header.Get("X-Kyren-Timestamp")
if !verifyWebhookSignature(payload, signature, timestamp, webhookSecret) {
http.Error(w, "Invalid signature", http.StatusBadRequest)
return
}
var event struct { ID string `json:"id"` }
if json.Unmarshal(body, &event) != nil || event.ID == "" {
http.Error(w, "Invalid event", http.StatusBadRequest)
return
}
if err := persistWebhookIfAbsent(event.ID, body); err != nil {
http.Error(w, "Retry later", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
重要安全注意事项:
- 处理事件前必须先验证签名
- 使用常量时间比较函数以防止时序攻击
- 拒绝时间戳超过 5 分钟(300000 毫秒)的请求以防止重放攻击
- 使用原始请求体进行签名验证(JSON 解析之前)
