hkdf.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 // import "golang.org/x/crypto/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. for len(p) > 0 {
  39. f.expander.Reset()
  40. f.expander.Write(f.prev)
  41. f.expander.Write(f.info)
  42. f.expander.Write([]byte{f.counter})
  43. f.prev = f.expander.Sum(f.prev[:0])
  44. f.counter++
  45. // Copy the new batch into p
  46. f.cache = f.prev
  47. n = copy(p, f.cache)
  48. p = p[n:]
  49. }
  50. // Save leftovers for next run
  51. f.cache = f.cache[n:]
  52. return need, nil
  53. }
  54. // New returns a new HKDF using the given hash, the secret keying material to expand
  55. // and optional salt and info fields.
  56. func New(hash func() hash.Hash, secret, salt, info []byte) io.Reader {
  57. if salt == nil {
  58. salt = make([]byte, hash().Size())
  59. }
  60. extractor := hmac.New(hash, salt)
  61. extractor.Write(secret)
  62. prk := extractor.Sum(nil)
  63. return &hkdf{hmac.New(hash, prk), extractor.Size(), info, 1, nil, nil}
  64. }