kdf.go 661 B

12345678910111213141516171819202122232425262728293031323334
  1. package aead
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha256"
  5. "hash"
  6. )
  7. func KDF(key []byte, path ...string) []byte {
  8. hmacCreator := &hMacCreator{value: []byte(KDFSaltConstVMessAEADKDF)}
  9. for _, v := range path {
  10. hmacCreator = &hMacCreator{value: []byte(v), parent: hmacCreator}
  11. }
  12. hmacf := hmacCreator.Create()
  13. hmacf.Write(key)
  14. return hmacf.Sum(nil)
  15. }
  16. type hMacCreator struct {
  17. parent *hMacCreator
  18. value []byte
  19. }
  20. func (h *hMacCreator) Create() hash.Hash {
  21. if h.parent == nil {
  22. return hmac.New(sha256.New, h.value)
  23. }
  24. return hmac.New(h.parent.Create, h.value)
  25. }
  26. func KDF16(key []byte, path ...string) []byte {
  27. r := KDF(key, path...)
  28. return r[:16]
  29. }