duanjiao5543 2018-11-10 19:53
浏览 154
已采纳

在Go中验证GitHub Webhook HMAC签名

I've written the following function for validating the X-Hub-Signature request header returned by the GitHub API as part of the webhook's payload.

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
", 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
", err)
        return false
    }

    expectedHash := hex.EncodeToString(hash.Sum(nil))
    log.Println("EXPECTED HASH:", expectedHash)
    return gotHash[1] == expectedHash
}

However, this doesn't seem to work as I'm not able to validate with the correct secret. Here is an example output, if that helps:

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

I've used the logic from hmac-examples repo as a guideline and implemented the code. However, I am unable to understand the reason behind this discrepancy.

I would be grateful if someone can point out the trivial mistake I'm making here.

Refer: Delivery Headers

  • 写回答

1条回答 默认 最新

  • dsa1234569 2018-11-10 20:12
    关注

    This is really embarrasing but still I would like to share how I was able to fix it.

    I sent in the wrong key as the input which was causing all the confusion.

    Lessons learnt:

    1. The above code snippet is absolutely correct and can be used as a validator.
    2. Every one makes stupid mistakes but only the wise own up to them and rectify.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试