| 1 |
// Copyright 2014 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package hkdf_test |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"crypto/hkdf" |
| 10 |
"crypto/rand" |
| 11 |
"crypto/sha256" |
| 12 |
"fmt" |
| 13 |
) |
| 14 |
|
| 15 |
// Usage example that expands one master secret into three other |
| 16 |
// cryptographically secure keys. |
| 17 |
func Example_usage() { |
| 18 |
// Underlying hash function for HMAC. |
| 19 |
hash := sha256.New |
| 20 |
keyLen := hash().Size() |
| 21 |
|
| 22 |
// Cryptographically secure master secret. |
| 23 |
secret := []byte{0x00, 0x01, 0x02, 0x03} // i.e. NOT this. |
| 24 |
|
| 25 |
// Non-secret salt, optional (can be nil). |
| 26 |
// Recommended: hash-length random value. |
| 27 |
salt := make([]byte, hash().Size()) |
| 28 |
if _, err := rand.Read(salt); err != nil { |
| 29 |
panic(err) |
| 30 |
} |
| 31 |
|
| 32 |
// Non-secret context info, optional (can be nil). |
| 33 |
info := "hkdf example" |
| 34 |
|
| 35 |
// Generate three 128-bit derived keys. |
| 36 |
var keys [][]byte |
| 37 |
for i := 0; i < 3; i++ { |
| 38 |
key, err := hkdf.Key(hash, secret, salt, info, keyLen) |
| 39 |
if err != nil { |
| 40 |
panic(err) |
| 41 |
} |
| 42 |
keys = append(keys, key) |
| 43 |
} |
| 44 |
|
| 45 |
for i := range keys { |
| 46 |
fmt.Printf("Key #%d: %v\n", i+1, !bytes.Equal(keys[i], make([]byte, 16))) |
| 47 |
} |
| 48 |
|
| 49 |
// Output: |
| 50 |
// Key #1: true |
| 51 |
// Key #2: true |
| 52 |
// Key #3: true |
| 53 |
} |