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 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助