hkdf.go 879 B

12345678910111213141516171819202122232425262728
  1. // Copyright (c) 2021 Tulir Asokan
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. // Package hkdfutil contains a simple wrapper for golang.org/x/crypto/hkdf that reads a specified number of bytes.
  7. package hkdfutil
  8. import (
  9. "crypto/sha256"
  10. "fmt"
  11. "golang.org/x/crypto/hkdf"
  12. )
  13. func SHA256(key, salt, info []byte, length uint8) []byte {
  14. data := make([]byte, length)
  15. h := hkdf.New(sha256.New, key, salt, info)
  16. n, err := h.Read(data)
  17. if err != nil {
  18. // Length is limited to 255 by being uint8, so these errors can't actually happen
  19. panic(fmt.Errorf("failed to expand key: %w", err))
  20. } else if uint8(n) != length {
  21. panic(fmt.Errorf("didn't read enough bytes (got %d, wanted %d)", n, length))
  22. }
  23. return data
  24. }