Skip to content

HMAC Basics in Go

In cryptography, a keyed-hash message authentication code (HMAC) is a specific type of message authentication code (MAC). It involves a cryptographic hash function in combination with a secret cryptographic key. As with any message authentication code, it may be used to simultaneously verify both the data integrity and the authentication of a message.

Any cryptographic hash function, such as SHA-1 or MD5, may be used in the calculation of an HMAC. The resulting MAC algorithm is termed HMAC-SHA1 or HMAC-MD5 accordingly.

The cryptographic strength of the HMAC depends upon the cryptographic strength of the underlying hash function, the size of its hash output, and on the size and quality of the key.

Basic example:

package main

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

func main() {
	c1 := calculateCode("[email protected]")
	fmt.Println(c1)
}

func calculateCode(s string) string {
	h := hmac.New(sha256.New, []byte("ourtestkey"))
	io.WriteString(h, s)
	return fmt.Sprintf("%x", h.Sum(nil))
}

Run it in the go playground.