登录
首页 >  Golang >  Go问答

在 Go 中验证 GitHub Webhook HMAC 签名

来源:stackoverflow

时间:2024-03-17 15:36:28 113浏览 收藏

在 Go 中验证 GitHub Webhook HMAC 签名时,确保使用正确的密钥至关重要。开发人员在实现验证逻辑时常犯的错误是使用错误的密钥,导致无法验证签名。本文将讨论在 Go 中正确验证 GitHub Webhook HMAC 签名所需的步骤,并提供一个经过测试且有效的代码示例。

问题内容

我编写了以下函数,用于验证 github api 作为 webhook 负载的一部分返回的 x-hub-signature 请求标头。

func isvalidsignature(r *http.request, key string) bool {
    // assuming a non-empty header
    gothash := strings.splitn(r.header.get("x-hub-signature"), "=", 2)
    if gothash[0] != "sha1" {
        return false
    }
    defer r.body.close()

    b, err := ioutil.readall(r.body)
    if err != nil {
        log.printf("cannot read the request body: %s\n", err)
        return false
    }

    hash := hmac.new(sha1.new, []byte(key))
    if _, err := hash.write(b); err != nil {
        log.printf("cannot compute the hmac for request: %s\n", err)
        return false
    }

    expectedhash := hex.encodetostring(hash.sum(nil))
    log.println("expected hash:", expectedhash)
    return gothash[1] == expectedhash
}

但是,这似乎不起作用,因为我无法使用正确的 secret 进行验证。这是一个示例输出,如果有帮助的话:

HUB SIGNATURE: sha1=026b77d2284bb95aa647736c42f32ea821d6894d
EXPECTED HASH: 86b6fa48bf7643494dc3a8459a8af70008f6881a

我使用 hmac-examples 存储库中的逻辑作为指导并实现了代码。但是,我无法理解这种差异背后的原因。

如果有人能指出我在这里犯的小错误,我将不胜感激。

参考:交付标头


解决方案


这确实很尴尬,但我仍然想分享我是如何解决这个问题的。

我发送了错误的 key 作为输入,这导致了所有混乱。

经验教训:

  1. 上面的代码片段绝对正确并且可以用作验证器。
  2. 每个人都会犯愚蠢的错误,但只有智者才能承认错误并改正。

本篇关于《在 Go 中验证 GitHub Webhook HMAC 签名》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>