簽名演算法
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 解析之前)
