前几天做过类似 GitHub 的 webhook , 如果是 HMAC MD5 加密,还得看是不是 sha256 ,
当时我的比较是这样的 :
```js
function compareSignatures(signature, rawBody, secretKey) {
const computedSignature = crypto.createHmac("sha256", secretKey)
.update(rawBody)
.digest("hex");
const hexSignature = signature.slice("sha256=".length);
const sig = Buffer.from(hexSignature, "utf8");
const digest = Buffer.from(computedSignature, "utf8");
return sig.length === digest.length && timingSafeEqual(digest, sig);
}
```
rawBody 就是你的 JSON body ,一定是不能转化的,express 有插件自动转化了,,secretKey 就是你自己设置的一串 Key ,生成的字段是类似 "fdaasdsa" 就是签名后面的一段"sha256=" 后面的一段,采用 Buffer 安全的比较,,当然我也是找的晚上的改了,
不行就参考 GitHub 的手册,很全面就是用的 ruby 语言示例:
https://docs.github.com/en/developers/webhooks-and-events/webhooks/securing-your-webhooks#validating-payloads-from-github