Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create HMAC_256 from a string in Golang

I am trying to generate a HMAC 256 hash from a message and secret. However when I return it, it is not correct.

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.

like image 249
Sebastian J Avatar asked Dec 25 '22 16:12

Sebastian J


1 Answers

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
like image 169
JimB Avatar answered Jan 08 '23 21:01

JimB