英文:
How to generate HMAC
问题
我需要在Go中创建一个Hmac。我已经在nodejs中创建了一个Hmac,现在需要在Go中生成相同的Hmac。我尝试了以下代码,但输出完全不同。我不知道我做错了什么。
这是我尝试的代码:
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"))
}
输出:JVN7kUPFL0aQ09lIH4YOsFJA3A2faqTuu6zIaYo61VI=
需要Go中等效的以下nodejs代码
var crypto = require('crypto'),
text = 'sms1',
key = 'b5fb5b3a65b8429693c3a029308e2e46';
var hash = crypto.createHmac('sha256', key)
hash.update(text)
var value = hash.digest('hex')
// 输出
25537b9143c52f4690d3d9481f860eb05240dc0d9f6aa4eebbacc8698a3ad552
请注意,这只是代码的翻译,我无法提供关于代码是否正确的任何保证。
英文:
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
得分: 14
你需要在Go程序中使用与Node.js程序相同的编码方式(十六进制):
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
英文:
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"))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论