dongwang6837 2016-09-10 12:29
浏览 179
已采纳

如何生成HMAC

I need to create an Hmac in Go. I have created an Hmac in nodejs, need to generate the same Hamc in Go. Tried following code but getting exactly different output. I don't know what I am doing wrong. This is what I tried

package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "fmt"
)

func ComputeHmac256(message string, secret string) string {
    key := []byte(secret)
    h := hmac.New(sha256.New, key)
    h.Write([]byte(message))
    return base64.StdEncoding.EncodeToString(h.Sum(nil))
}

func main() {
    fmt.Println(ComputeHmac256("sms1", "b5fb5b3a65b8429693c3a029308e2e46"))
}
Output: JVN7kUPFL0aQ09lIH4YOsFJA3A2faqTuu6zIaYo61VI=

Need go equivalent of following nodejs code

var crypto = require('crypto'),
    text = 'sms1',
    key = 'b5fb5b3a65b8429693c3a029308e2e46'
var hash = crypto.createHmac('sha256', key)
hash.update(text)
var value = hash.digest('hex')
// Output 
25537b9143c52f4690d3d9481f860eb05240dc0d9f6aa4eebbacc8698a3ad552
  • 写回答

1条回答 默认 最新

  • drnl10253 2016-09-10 12:35
    关注

    You need to use the same encoding in your Go program as you do in your Node.js program (hex):

    package main
    
    import (
        "crypto/hmac"
        "crypto/sha256"
        "encoding/hex"
        "fmt"
    )
    
    func ComputeHmac256(message string, secret string) string {
        key := []byte(secret)
        h := hmac.New(sha256.New, key)
        h.Write([]byte(message))
        return hex.EncodeToString(h.Sum(nil))
    }
    
    func main() {
        fmt.Println(ComputeHmac256("sms1", "b5fb5b3a65b8429693c3a029308e2e46"))
    }
    

    https://play.golang.org/p/-1yePFeipT

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用