在Golang中从字符串创建HMAC_256。

huangapple go评论92阅读模式
英文:

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(&quot;secret&quot;))
	key := secretHash.Sum(nil)
	fmt.Println(&quot;The secret key is &quot;, hex.EncodeToString(key))

 	message := strings.Join([]string{&quot;one&quot;, &quot;two&quot;, &quot;three&quot;}, &quot;&quot;)
	fmt.Println(&quot;The message is &quot;, 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:

&quot;^\xbe&quot;\x94\xec\xd0\xe0\xf0\x8e\xabv\x90\xd2\xa6\xeei&quot;

Using the strings directly should show the difference: http://play.golang.org/p/wteqLNcnTV

Which prints

3f0ee534c3d86cb16f4413fe1a76a12f94449f751f7d632cd87f24b94e76c710

huangapple
  • 本文由 发表于 2015年8月6日 00:37:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/31838189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定