hmac.go 714 B

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