Go Cheatsheet - Hmac

·

1 min read

Hmac

Use crypto/hmac to calculate message authentication code.

hmac & use md5 as digest method

package main

import (
    "fmt"
    "crypto/hmac"
    "crypto/md5"
)

func main() {
    key := []byte("hello")
    msg := []byte("world")
    mac := hmac.New(md5.New, key)
    mac.Write(msg)
    digest := mac.Sum(nil)
    fmt.Println(fmt.Sprintf("%x", digest))
}

Run:

0e2564b7e100f034341ea477c23f283b

hmac & use sha256 as digest method

package main

import (
    "fmt"
    "crypto/hmac"
    "crypto/sha256"
)

func main() {
    key := []byte("hello")
    msg := []byte("world")
    mac := hmac.New(sha256.New, key)
    mac.Write(msg)
    digest := mac.Sum(nil)
    fmt.Println(fmt.Sprintf("%x", digest))
}

Run:

f1ac9702eb5faf23ca291a4dc46deddeee2a78ccdaf0a412bed7714cfffb1cc4

Compare to value generated by Python

import hashlib
print(hmac.new(b'hello', b'world', hashlib.md5).hexdigest())
# 0e2564b7e100f034341ea477c23f283b
print(hmac.new(b'hello', b'world', hashlib.sha256).hexdigest())
# f1ac9702eb5faf23ca291a4dc46deddeee2a78ccdaf0a412bed7714cfffb1cc4