hkdf.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 implements the HMAC-based Extract-and-Expand Key Derivation
  5. // Function (HKDF) as defined in RFC 5869.
  6. //
  7. // HKDF is a cryptographic key derivation function (KDF) with the goal of
  8. // expanding limited input keying material into one or more cryptographically
  9. // strong secret keys.
  10. //
  11. // RFC 5869: https://tools.ietf.org/html/rfc5869
  12. package hkdf
  13. import (
  14. "crypto/hmac"
  15. "errors"
  16. "hash"
  17. "io"
  18. )
  19. type hkdf struct {
  20. expander hash.Hash
  21. size int
  22. info []byte
  23. counter byte
  24. prev []byte
  25. cache []byte
  26. }
  27. func (f *hkdf) Read(p []byte) (int, error) {
  28. // Check whether enough data can be generated
  29. need := len(p)
  30. remains := len(f.cache) + int(255-f.counter+1)*f.size
  31. if remains < need {
  32. return 0, errors.New("hkdf: entropy limit reached")
  33. }
  34. // Read from the cache, if enough data is present
  35. n := copy(p, f.cache)
  36. p = p[n:]
  37. // Fill the buffer
  38. var input []byte
  39. for len(p) > 0 {
  40. input = append(f.prev, f.info...)
  41. input = append(input, f.counter)
  42. f.expander.Reset()
  43. f.expander.Write(input)
  44. f.prev = f.expander.Sum(f.prev[:0])
  45. f.counter++
  46. // Copy the new batch into p
  47. f.cache = f.prev
  48. n = copy(p, f.cache)
  49. p = p[n:]
  50. }
  51. // Save leftovers for next run
  52. f.cache = f.cache[n:]
  53. return need, nil
  54. }
  55. // New returns a new HKDF using the given hash, the secret keying material to expand
  56. // and optional salt and info fields.
  57. func New(hash func() hash.Hash, secret, salt, info []byte) io.Reader {
  58. if salt == nil {
  59. salt = make([]byte, hash().Size())
  60. }
  61. extractor := hmac.New(hash, salt)
  62. extractor.Write(secret)
  63. prk := extractor.Sum(nil)
  64. return &hkdf{hmac.New(hash, prk), extractor.Size(), info, 1, nil, nil}
  65. }