keyDerivation.go 907 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package rfc4757
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "golang.org/x/crypto/md4"
  9. )
  10. // StringToKey returns a key derived from the string provided according to the definition in RFC 4757.
  11. func StringToKey(secret string) ([]byte, error) {
  12. b := make([]byte, len(secret)*2, len(secret)*2)
  13. for i, r := range secret {
  14. u := fmt.Sprintf("%04x", r)
  15. c, err := hex.DecodeString(u)
  16. if err != nil {
  17. return []byte{}, errors.New("character could not be encoded")
  18. }
  19. // Swap round the two bytes to make little endian as we put into byte slice
  20. b[2*i] = c[1]
  21. b[2*i+1] = c[0]
  22. }
  23. r := bytes.NewReader(b)
  24. h := md4.New()
  25. _, err := io.Copy(h, r)
  26. if err != nil {
  27. return []byte{}, err
  28. }
  29. return h.Sum(nil), nil
  30. }
  31. func deriveKeys(key, checksum []byte, usage uint32, export bool) (k1, k2, k3 []byte) {
  32. k1 = key
  33. k2 = HMAC(k1, UsageToMSMsgType(usage))
  34. k3 = HMAC(k2, checksum)
  35. return
  36. }