Generating a SHA256 HMAC in Go

SHA256 being vulnerable to length-extension attacks, you need to use the special HMAC construction to securely sign data with SHA256 and a secret key.

Here is how to do it in Go.

package main

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
)

func main() {
	// create a random 64 bytes (512 bits) secret
	secret := make([]byte, 64)
	_, err := rand.Read(secret)
	if err != nil {
		fmt.Println("error generating a random secret:", err)
		return
	}

	data := []byte("Hello World")

	// create a new HMAC by defining the hash type and the key
	hmac := hmac.New(sha256.New, secret)

	// compute the HMAC
	hmac.Write([]byte(data))
	dataHmac := hmac.Sum(nil)

	hmacHex := hex.EncodeToString(dataHmac)
	secretHex := hex.EncodeToString(secret)

	fmt.Printf("HMAC_SHA256(key: %s, data: %s): %s", secretHex, string(data), hmacHex)
}
1 email / week to learn how to (ab)use technology for fun & profit: Programming, Hacking & Entrepreneurship.
I hate spam even more than you do. I'll never share your email, and you can unsubscribe at any time.

Tags: hacking, go, programming, cryptography

Want to learn Rust, Cryptography and Security? Get my book Black Hat Rust!