Created
August 24, 2022 16:16
-
-
Save ericlagergren/98cbd747dd075037d896b341d3ecbce7 to your computer and use it in GitHub Desktop.
hkdf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/hmac" | |
"crypto/sha256" | |
"fmt" | |
"hash" | |
"io" | |
"golang.org/x/crypto/hkdf" | |
) | |
func main() { | |
ikm := make([]byte, 32) | |
info := []byte("info") | |
b := test2(sha256.New, ikm, nil, info) | |
fmt.Printf("hkdf %x\n", b) | |
a := test1(sha256.New, ikm, nil, info) | |
fmt.Printf("hmac %x\n", a) | |
} | |
// test1 performs HMAC(key=HMAC(key=salt, data=ikm), data=info). | |
func test1(hash func() hash.Hash, ikm, salt, info []byte) []byte { | |
if salt == nil { | |
salt = make([]byte, hash().Size()) | |
} | |
// HMAC(key=salt, data=ikm) | |
extractor := hmac.New(hash, salt) | |
extractor.Write(ikm) | |
prk := extractor.Sum(nil) | |
// HMAC(key=prk, data=info || 1) | |
expander := hmac.New(hash, prk) | |
expander.Write(info) | |
expander.Write([]byte{1}) | |
return expander.Sum(nil) | |
} | |
// test2 returns HKDF-Extract and HKDF-Expand. | |
func test2(hash func() hash.Hash, ikm, salt, info []byte) []byte { | |
key := make([]byte, sha256.Size) | |
r := hkdf.New(hash, ikm, salt, info) | |
if _, err := io.ReadFull(r, key); err != nil { | |
panic(err) | |
} | |
return key | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment