通过 HMAC 校验 Webhook 签名
Chaingateway Webhook 的 X-Signature header 让你确认请求确实来自 Chaingateway。它包含 payload 中交易 id(txid)的 HMAC-SHA256 的 base64 编码,密钥是你的个人密钥(personal secret)。你的接收端重新计算该值并与 header 比较。设置个人密钥之后,才会发送该 header。
X-Signature header 能防范什么?
Section titled “X-Signature header 能防范什么?”它防范的是伪造的请求:任何人都可以向你公开的接收端 URL 发送 POST 请求,但只有知道个人密钥的发送方才能生成匹配的签名。HMAC 由 RFC 2104 定义,它把哈希函数与密钥结合起来,这里使用的是 SHA-256。NIST FIPS 198-1 以带密钥哈希消息认证码(Keyed-Hash Message Authentication Code)的名称规定了同一种构造。
签名只覆盖 txid,不包含其他内容。请求体中的金额、地址和代币字段都没有被签名。因此,一对有效的 txid 和签名并不能证明请求体的其余部分没有被改动。校验通过后,请把 txid 当作查询键:用 GET /api/v2/{chain}/transactions/{txid} 读取该交易,并根据 API 返回的数据入账,而不是根据通知请求体中的金额。
如何设置个人密钥?
Section titled “如何设置个人密钥?”你可以在个人资料设置中设置或重新生成个人密钥。请按以下步骤操作:
- 打开个人资料设置。
- 找到标记为 “Personal Secret” 的部分。
- 如果尚未设置密钥,点击 “Set Personal Secret” 生成一个。如果已有密钥,点击 “Regenerate Secret” 替换它。
对于正在运行的系统,有两点需要注意。如果你还没有个人密钥,添加一个就会为所有发出的 Webhook 启用 X-Signature header。请在这样做之前,先部署一个能接受并校验该 header 的接收端。如果你重新生成已有的密钥,新密钥会立即对 Webhook 通知生效。请同时更新接收端,否则它会拒绝有效的请求。
X-Signature header 是如何构建的?
Section titled “X-Signature header 是如何构建的?”Chaingateway 从 payload 中读取 txid,以个人密钥为密钥,用 SHA-256 哈希函数对它计算 HMAC,再把得到的 32 个字节做 base64 编码。txid 是唯一的交易标识符,已经出现在 Webhook 请求体中,所以接收端拥有重新计算该值所需的全部信息。该密钥只在 Chaingateway 和你之间共享。
如何在我的代码中校验签名?
Section titled “如何在我的代码中校验签名?”根据请求体中的 txid 重新计算 HMAC,并与 header 的值比较。请使用恒定时间的比较函数,这样比较所耗的时间不会泄露期望值的任何信息。下面的示例分别用 Python、Java、PHP 和 JavaScript 完成这件事。
import hmacimport hashlibimport base64
def verify_signature(txid, received_signature, personal_secret): # Generate the expected signature expected_signature = base64.b64encode(hmac.new( personal_secret.encode(), txid.encode(), hashlib.sha256 ).digest()).decode()
# Compare the expected signature with the received signature return hmac.compare_digest(expected_signature, received_signature)
# Example usagetxid = 'your_txid_here'received_signature = 'received_signature_here'personal_secret = 'your_personal_secret_here'
if verify_signature(txid, received_signature, personal_secret): print("Signature is valid.")else: print("Invalid signature.")import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.util.Base64;
public class SignatureVerifier { public static boolean verifySignature(String txid, String receivedSignature, String personalSecret) throws Exception { Mac mac = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKeySpec = new SecretKeySpec(personalSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); mac.init(secretKeySpec);
byte[] signatureBytes = mac.doFinal(txid.getBytes(StandardCharsets.UTF_8)); String expectedSignature = Base64.getEncoder().encodeToString(signatureBytes);
// Constant-time comparison return MessageDigest.isEqual( expectedSignature.getBytes(StandardCharsets.UTF_8), receivedSignature.getBytes(StandardCharsets.UTF_8)); }
public static void main(String[] args) { try { String txid = "your_txid_here"; String receivedSignature = "received_signature_here"; String personalSecret = "your_personal_secret_here";
if (verifySignature(txid, receivedSignature, personalSecret)) { System.out.println("Signature is valid."); } else { System.out.println("Invalid signature."); } } catch (Exception e) { e.printStackTrace(); } }}<?phpfunction verifySignature($txid, $receivedSignature, $personalSecret) { // Generate the expected signature $expectedSignature = base64_encode(hash_hmac('sha256', $txid, $personalSecret, true));
// Compare the expected signature with the received signature return hash_equals($expectedSignature, $receivedSignature);}
// Example usage$txid = 'your_txid_here';$receivedSignature = 'received_signature_here';$personalSecret = 'your_personal_secret_here';
if (verifySignature($txid, $receivedSignature, $personalSecret)) { echo "Signature is valid.";} else { echo "Invalid signature.";}const crypto = require('crypto');
function verifySignature(txid, receivedSignature, personalSecret) { // Generate the expected signature const expectedSignature = crypto .createHmac('sha256', personalSecret) .update(txid) .digest('base64');
// timingSafeEqual throws if the lengths differ, so check them first const expected = Buffer.from(expectedSignature); const received = Buffer.from(receivedSignature); return expected.length === received.length && crypto.timingSafeEqual(expected, received);}
// Example usageconst txid = 'your_txid_here';const receivedSignature = 'received_signature_here';const personalSecret = 'your_personal_secret_here';
if (verifySignature(txid, receivedSignature, personalSecret)) { console.log("Signature is valid.");} else { console.log("Invalid signature.");}如何测试我的校验代码?
Section titled “如何测试我的校验代码?”在把校验函数接入真实流量之前,请先用固定的输入测试它。下面的值是一组测试向量,你可以用任何 HMAC-SHA256 工具复现。其中的密钥是占位符,不是真实的个人密钥。如果你的函数对这组输入返回了不同的值,问题出在你的代码里,而不在 Webhook 上。
personal_secret: my_personal_secrettxid: 18f52f2a55b94a6e3705de4abb18e95dfce79970f27b29450705c561e12b6988X-Signature: t2vU2mYBCv/UvpKprNJB7qbgrCpPXKb6NWgL77xsZgQ=常见的错误有:对整个 JSON 请求体而不是 txid 做哈希;使用十六进制摘要而不是 base64;用 == 比较,它不是恒定时间的。还要记住,个人密钥对整个账户生效。你在个人资料设置中重新生成的密钥,会一次性改变该账户所有 Webhook 的签名。
签名不匹配时我该怎么办?
Section titled “签名不匹配时我该怎么办?”请用 401 或 403 这类错误状态码拒绝该请求,并且不要处理请求体。请记录 txid、收到的 header 和来源地址,这样你就能分辨是密钥配置有误,还是请求被伪造。如果同一个发送方在你重新生成密钥之后立刻出现不匹配,说明接收端仍在使用旧密钥。只猜测 txid 的伪造请求,在没有密钥的情况下无法生成有效的签名。
Webhook 接收端还应该做什么?
Section titled “Webhook 接收端还应该做什么?”签名校验只是其中一层。下面这些措施覆盖其余的链路。
- 通过 HTTPS 提供接收端服务,这样 payload 在传输中是加密的。OWASP 的 REST Security Cheat Sheet 建议,所有处理敏感数据的端点都使用 HTTPS。
- 对缺少
X-Signature或签名错误的请求,用错误状态码拒绝并记录日志。 - 把
txid用作幂等键。用POST /api/v2/{chain}/webhooks/notifications/{id}/retry重新发送的通知带有相同的txid,不得重复入账。 - 把个人密钥放在密钥存储中,绝不要放进代码仓库,如果它可能已经泄露,请轮换它。Chaingateway 不会自行重试失败的投递,所以请把接收端和密钥的更新规划为同一步操作,之后再从失败列表中重新发送错过的通知。