Skip to content

Commit d2c3f1d

Browse files
committed
hkdf: improve example
Change-Id: I540c699baf1f7cbf27da458961d581773f442864 Reviewed-on: https://go-review.googlesource.com/c/144397 Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org> Reviewed-by: Adam Langley <agl@golang.org>
1 parent 85e1b3f commit d2c3f1d

File tree

1 file changed

+25
-30
lines changed

1 file changed

+25
-30
lines changed

hkdf/example_test.go

Lines changed: 25 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -9,49 +9,44 @@ import (
99
"crypto/rand"
1010
"crypto/sha256"
1111
"fmt"
12-
"golang.org/x/crypto/hkdf"
1312
"io"
13+
14+
"golang.org/x/crypto/hkdf"
1415
)
1516

16-
// Usage example that expands one master key into three other cryptographically
17-
// secure keys.
17+
// Usage example that expands one master secret into three other
18+
// cryptographically secure keys.
1819
func Example_usage() {
19-
// Underlying hash function to use
20+
// Underlying hash function for HMAC.
2021
hash := sha256.New
2122

22-
// Cryptographically secure master key.
23-
master := []byte{0x00, 0x01, 0x02, 0x03} // i.e. NOT this.
23+
// Cryptographically secure master secret.
24+
secret := []byte{0x00, 0x01, 0x02, 0x03} // i.e. NOT this.
2425

25-
// Non secret salt, optional (can be nil)
26-
// Recommended: hash-length sized random
26+
// Non-secret salt, optional (can be nil).
27+
// Recommended: hash-length random value.
2728
salt := make([]byte, hash().Size())
28-
n, err := io.ReadFull(rand.Reader, salt)
29-
if n != len(salt) || err != nil {
30-
fmt.Println("error:", err)
31-
return
29+
if _, err := rand.Read(salt); err != nil {
30+
panic(err)
3231
}
3332

34-
// Non secret context specific info, optional (can be nil).
35-
// Note, independent from the master key.
36-
info := []byte{0x03, 0x14, 0x15, 0x92, 0x65}
37-
38-
// Create the key derivation function
39-
hkdf := hkdf.New(hash, master, salt, info)
40-
41-
// Generate the required keys
42-
keys := make([][]byte, 3)
43-
for i := 0; i < len(keys); i++ {
44-
keys[i] = make([]byte, 24)
45-
n, err := io.ReadFull(hkdf, keys[i])
46-
if n != len(keys[i]) || err != nil {
47-
fmt.Println("error:", err)
48-
return
33+
// Non-secret context info, optional (can be nil).
34+
info := []byte("hkdf example")
35+
36+
// Generate three 128-bit derived keys.
37+
hkdf := hkdf.New(hash, secret, salt, info)
38+
39+
var keys [][]byte
40+
for i := 0; i < 3; i++ {
41+
key := make([]byte, 16)
42+
if _, err := io.ReadFull(hkdf, key); err != nil {
43+
panic(err)
4944
}
45+
keys = append(keys, key)
5046
}
5147

52-
// Keys should contain 192 bit random keys
53-
for i := 1; i <= len(keys); i++ {
54-
fmt.Printf("Key #%d: %v\n", i, !bytes.Equal(keys[i-1], make([]byte, 24)))
48+
for i := range keys {
49+
fmt.Printf("Key #%d: %v\n", i+1, !bytes.Equal(keys[i], make([]byte, 16)))
5550
}
5651

5752
// Output:

0 commit comments

Comments
 (0)