Derive secure keys in Go with HKDF and SHA256

HKDF is a key derivation function based on the HMAC function.

Key Derivation Functions (KDF) are used to generate secure "subkeys" from an already cryptographically secure "master" (or root) key. If you want different keys for encryption and for authentication, for example.

Here is how to derive a subkey from a master key in Go.

package main

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"

	"golang.org/x/crypto/hkdf"
)

func main() {
	// create a random 32 bytes (256 bits) master key
	masterKey := make([]byte, 32)
	_, err := rand.Read(masterKey)
	if err != nil {
		fmt.Println("error generating the master key:", err)
		return
	}

	// info is used to separate the different subkeys
	info := []byte("auth_key")
	subKey := make([]byte, 32)

	// salt can be nil
	hkdf := hkdf.New(sha256.New, masterKey, nil, info)
	_, err = io.ReadFull(hkdf, subKey)
	if err != nil {
		fmt.Println("error deriving the subkey:", err)
		return
	}

	fmt.Printf("HKDF_SHA256(key: %s, info: %s): %s", hex.EncodeToString(masterKey), string(info), hex.EncodeToString(subKey))
}
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!