Dibish Dibish - 3 months ago 50
Node.js Question

Go lang generate hmac

Am new to go language, I need to create an Hmac in go language. I have created an Hmac in nodejs, need to generate the same Hamc in go language. Tried following code but getting exactly different output. I dont 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

Answer

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