example_test.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. package hkdf_test
  5. import (
  6. "bytes"
  7. "crypto/rand"
  8. "crypto/sha256"
  9. "fmt"
  10. "io"
  11. "golang.org/x/crypto/hkdf"
  12. )
  13. // Usage example that expands one master secret into three other
  14. // cryptographically secure keys.
  15. func Example_usage() {
  16. // Underlying hash function for HMAC.
  17. hash := sha256.New
  18. // Cryptographically secure master secret.
  19. secret := []byte{0x00, 0x01, 0x02, 0x03} // i.e. NOT this.
  20. // Non-secret salt, optional (can be nil).
  21. // Recommended: hash-length random value.
  22. salt := make([]byte, hash().Size())
  23. if _, err := rand.Read(salt); err != nil {
  24. panic(err)
  25. }
  26. // Non-secret context info, optional (can be nil).
  27. info := []byte("hkdf example")
  28. // Generate three 128-bit derived keys.
  29. hkdf := hkdf.New(hash, secret, salt, info)
  30. var keys [][]byte
  31. for i := 0; i < 3; i++ {
  32. key := make([]byte, 16)
  33. if _, err := io.ReadFull(hkdf, key); err != nil {
  34. panic(err)
  35. }
  36. keys = append(keys, key)
  37. }
  38. for i := range keys {
  39. fmt.Printf("Key #%d: %v\n", i+1, !bytes.Equal(keys[i], make([]byte, 16)))
  40. }
  41. // Output:
  42. // Key #1: true
  43. // Key #2: true
  44. // Key #3: true
  45. }