英文:
Create HMAC_256 from a string in Golang
问题
我正在尝试从消息和密钥生成一个HMAC 256哈希值。然而,当我返回它时,结果是不正确的。
func makeSig(s Signature) string {
secretHash := md5.New()
secretHash.Write([]byte("secret"))
key := secretHash.Sum(nil)
fmt.Println("The secret key is ", hex.EncodeToString(key))
message := strings.Join([]string{"one", "two", "three"}, "")
fmt.Println("The message is ", message)
sig := hmac.New(sha256.New, key)
sig.Write([]byte(message))
return hex.EncodeToString(sig.Sum(nil))
}
我不确定问题出在哪里,请给予指导。
英文:
I am trying to generate a HMAC 256 hash from a message and secret. However when I return it, it is not correct.
<!-- language: go -->
func makeSig(s Signature) string {
secretHash := md5.New()
secretHash.Write([]byte("secret"))
key := secretHash.Sum(nil)
fmt.Println("The secret key is ", hex.EncodeToString(key))
message := strings.Join([]string{"one", "two", "three"}, "")
fmt.Println("The message is ", message)
sig := hmac.New(sha256.New, key)
sig.Write([]byte(message))
return hex.EncodeToString(sig.Sum(nil))
}
I'm not sure what's wrong, please advise.
答案1
得分: 12
你正在打印你的“密钥”的十六进制编码版本,但你正在使用未编码的原始字节作为该密钥。
在示例中,你打印的密钥是:
5ebe2294ecd0e0f08eab7690d2a6ee69
但你将其提供给hmac的是:
[]byte{0x5e, 0xbe, 0x22, 0x94, 0xec, 0xd0, 0xe0, 0xf0, 0x8e, 0xab, 0x76, 0x90, 0xd2, 0xa6, 0xee, 0x69}
作为字符串,它看起来像:
"^¾"\x94\xec\xd0\xe0\xf0\x8e\xabv\x90\xd2\xa6\xeei"
直接使用字符串应该显示出差异:http://play.golang.org/p/wteqLNcnTV
它打印出:
3f0ee534c3d86cb16f4413fe1a76a12f94449f751f7d632cd87f24b94e76c710
英文:
You're printing out the hex encoded version of your "key", but you're using the raw, unencoded bytes for that key.
Your key in the example is printed as:
5ebe2294ecd0e0f08eab7690d2a6ee69
but you're giving this to the hmac:
[]byte{0x5e, 0xbe, 0x22, 0x94, 0xec, 0xd0, 0xe0, 0xf0, 0x8e, 0xab, 0x76, 0x90, 0xd2, 0xa6, 0xee, 0x69}
which as a string, looks like:
"^\xbe"\x94\xec\xd0\xe0\xf0\x8e\xabv\x90\xd2\xa6\xeei"
Using the strings directly should show the difference: http://play.golang.org/p/wteqLNcnTV
Which prints
3f0ee534c3d86cb16f4413fe1a76a12f94449f751f7d632cd87f24b94e76c710
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论