Golang Gitee Webhook 签名验证

Gitee WebHook 提供WebHook 密钥验证和验证算法,原文地址

  1. 把timestamp+"\n"+密钥当做签名字符串,使用HmacSHA256算法计算签名。

  2. 对上述得到的结果进行 Base64 encode。

  3. 对上述得到的结果进行 urlEncode,得到最终的签名(需要使用UTF-8字符集)。

  4. 由于网上参考别人的代码都是抄袭。而且还转了16进制,踩了半天的坑。hex.EncodeToString()转成16进制的字符串哦,出来结果不一致哦。

  5. 还有Go里面使用的是PathEscape这个方法,而QueryEscape出来结果不一致。

  6. 另外,Python3 中urllib.quote_plus出来的结果也不一致。

  7. Python3和Golang中,只需要base64加密后就可以验证了。

  8. 其余情况未遇到。

参考代码,请自行修改。

func GiteeSign(secret string, timestamp int64) string {
	stringToSign := fmt.Sprintf("%d\n%s", timestamp, secret)
	byteStringToSign := []byte(stringToSign)
	b64 := base64.StdEncoding.EncodeToString(HmacSha256Sign([]byte(secret), byteStringToSign))
	return url.PathEscape(b64)
}

func HmacSha256Sign(secret, msg []byte) []byte {
	h := hmac.New(sha256.New, []byte(secret))
	h.Write(msg)
	return h.Sum(nil)
}
posted @ 2022-07-11 16:14  咕咚!  阅读(300)  评论(0)    收藏  举报