hmac.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package hmac
  2. import (
  3. baseHmac "crypto/hmac"
  4. "crypto/sha1"
  5. "crypto/sha256"
  6. "encoding/base64"
  7. "encoding/hex"
  8. )
  9. var _ HMAC = (*hmac)(nil)
  10. type HMAC interface {
  11. i()
  12. Sha1ToString(data string) string
  13. Sha1ToBase64String(data string) string
  14. Sha256ToString(data string) string
  15. Sha256ToBase64String(data string) string
  16. }
  17. type hmac struct {
  18. secret string
  19. }
  20. func New(secret string) HMAC {
  21. return &hmac{secret: secret}
  22. }
  23. func (m *hmac) i() {}
  24. func (m *hmac) Sha256ToString(data string) string {
  25. h := baseHmac.New(sha256.New, []byte(m.secret))
  26. h.Write([]byte(data))
  27. return hex.EncodeToString(h.Sum(nil))
  28. }
  29. func (m *hmac) Sha256ToBase64String(data string) string {
  30. h := baseHmac.New(sha256.New, []byte(m.secret))
  31. h.Write([]byte(data))
  32. return base64.StdEncoding.EncodeToString(h.Sum(nil))
  33. }
  34. func (m *hmac) Sha1ToString(data string) string {
  35. h := baseHmac.New(sha1.New, []byte(m.secret))
  36. h.Write([]byte(data))
  37. return hex.EncodeToString(h.Sum(nil))
  38. }
  39. func (m *hmac) Sha1ToBase64String(data string) string {
  40. h := baseHmac.New(sha1.New, []byte(m.secret))
  41. h.Write([]byte(data))
  42. return base64.StdEncoding.EncodeToString(h.Sum(nil))
  43. }