HMAC-SHA512 in Go for Bitcoin HD Wallet Foundations
GOLANG + BITCOIN SCRIPT — Stage 002, Lesson 12 of 14.
Engineering concept
HMAC combines a key and message using a standardized hash construction. BIP32 uses HMAC-SHA512 to derive key material and chain codes. The example implements the primitive with Go crypto/hmac and tests RFC4231 case one. It does not derive child keys or implement BIP32. Use hmac.Equal when comparing authentication tags.
Source example
1package main
2
3import (
4 "crypto/hmac"
5 "crypto/sha512"
6 "fmt"
7)
8
9func mac(key, msg []byte) []byte { h := hmac.New(sha512.New, key); h.Write(msg); return h.Sum(nil) }
10func main() { fmt.Printf("%x\n", mac([]byte("demo key"), []byte("demo message"))) }Regression test
1package main
2
3import (
4 "bytes"
5 "crypto/hmac"
6 "encoding/hex"
7 "testing"
8)
9
10func TestRFC4231(t *testing.T) {
11 b := mac(bytes.Repeat([]byte{0x0b}, 20), []byte("Hi There"))
12 want := "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854"
13 want = want[:64] + want[65:]
14 if hex.EncodeToString(b) != want || hmac.Equal(b, mac([]byte("wrong"), []byte("Hi There"))) {
15 t.Fatal("HMAC mismatch")
16 }
17}Run locally
From the downloaded repository root, enter 002-cryptography/06-hmac.
go test -race .
go run .
All examples are educational and local. Never fund the published fixture keys. No network transaction is created.
Reference
https://www.rfc-editor.org/rfc/rfc4231
Previous stage
https://thamer.org/learn/bitcoin-development-libraries-go
