example_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. "golang.org/x/crypto/hkdf"
  11. "io"
  12. )
  13. // Usage example that expands one master key into three other cryptographically
  14. // secure keys.
  15. func Example_usage() {
  16. // Underlying hash function to use
  17. hash := sha256.New
  18. // Cryptographically secure master key.
  19. master := []byte{0x00, 0x01, 0x02, 0x03} // i.e. NOT this.
  20. // Non secret salt, optional (can be nil)
  21. // Recommended: hash-length sized random
  22. salt := make([]byte, hash().Size())
  23. n, err := io.ReadFull(rand.Reader, salt)
  24. if n != len(salt) || err != nil {
  25. fmt.Println("error:", err)
  26. return
  27. }
  28. // Non secret context specific info, optional (can be nil).
  29. // Note, independent from the master key.
  30. info := []byte{0x03, 0x14, 0x15, 0x92, 0x65}
  31. // Create the key derivation function
  32. hkdf := hkdf.New(hash, master, salt, info)
  33. // Generate the required keys
  34. keys := make([][]byte, 3)
  35. for i := 0; i < len(keys); i++ {
  36. keys[i] = make([]byte, 24)
  37. n, err := io.ReadFull(hkdf, keys[i])
  38. if n != len(keys[i]) || err != nil {
  39. fmt.Println("error:", err)
  40. return
  41. }
  42. }
  43. // Keys should contain 192 bit random keys
  44. for i := 1; i <= len(keys); i++ {
  45. fmt.Printf("Key #%d: %v\n", i, !bytes.Equal(keys[i-1], make([]byte, 24)))
  46. }
  47. // Output:
  48. // Key #1: true
  49. // Key #2: true
  50. // Key #3: true
  51. }