2018-01-28 14:56:30 +00:00
|
|
|
// Copyright 2014 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package hkdf_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/sha256"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2019-04-21 17:58:15 +00:00
|
|
|
|
|
|
|
"golang.org/x/crypto/hkdf"
|
2018-01-28 14:56:30 +00:00
|
|
|
)
|
|
|
|
|
2019-04-21 17:58:15 +00:00
|
|
|
// Usage example that expands one master secret into three other
|
|
|
|
// cryptographically secure keys.
|
2018-01-28 14:56:30 +00:00
|
|
|
func Example_usage() {
|
2019-04-21 17:58:15 +00:00
|
|
|
// Underlying hash function for HMAC.
|
2018-01-28 14:56:30 +00:00
|
|
|
hash := sha256.New
|
|
|
|
|
2019-04-21 17:58:15 +00:00
|
|
|
// Cryptographically secure master secret.
|
|
|
|
secret := []byte{0x00, 0x01, 0x02, 0x03} // i.e. NOT this.
|
2018-01-28 14:56:30 +00:00
|
|
|
|
2019-04-21 17:58:15 +00:00
|
|
|
// Non-secret salt, optional (can be nil).
|
|
|
|
// Recommended: hash-length random value.
|
2018-01-28 14:56:30 +00:00
|
|
|
salt := make([]byte, hash().Size())
|
2019-04-21 17:58:15 +00:00
|
|
|
if _, err := rand.Read(salt); err != nil {
|
|
|
|
panic(err)
|
2018-01-28 14:56:30 +00:00
|
|
|
}
|
|
|
|
|
2019-04-21 17:58:15 +00:00
|
|
|
// Non-secret context info, optional (can be nil).
|
|
|
|
info := []byte("hkdf example")
|
|
|
|
|
|
|
|
// Generate three 128-bit derived keys.
|
|
|
|
hkdf := hkdf.New(hash, secret, salt, info)
|
|
|
|
|
|
|
|
var keys [][]byte
|
|
|
|
for i := 0; i < 3; i++ {
|
|
|
|
key := make([]byte, 16)
|
|
|
|
if _, err := io.ReadFull(hkdf, key); err != nil {
|
|
|
|
panic(err)
|
2018-01-28 14:56:30 +00:00
|
|
|
}
|
2019-04-21 17:58:15 +00:00
|
|
|
keys = append(keys, key)
|
2018-01-28 14:56:30 +00:00
|
|
|
}
|
|
|
|
|
2019-04-21 17:58:15 +00:00
|
|
|
for i := range keys {
|
|
|
|
fmt.Printf("Key #%d: %v\n", i+1, !bytes.Equal(keys[i], make([]byte, 16)))
|
2018-01-28 14:56:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Output:
|
|
|
|
// Key #1: true
|
|
|
|
// Key #2: true
|
|
|
|
// Key #3: true
|
|
|
|
}
|