Dibish
Dibish

Reputation: 9293

How to generate HMAC

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

Upvotes: 2

Views: 3391

Answers (1)

user142162
user142162

Reputation:

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

Upvotes: 14

Related Questions