base-golang/pkg/hmac/hmac.go

56 lines
1.1 KiB
Go
Raw Permalink Normal View History

2024-07-23 10:23:43 +08:00
package hmac
import (
baseHmac "crypto/hmac"
"crypto/sha1"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
)
var _ HMAC = (*hmac)(nil)
type HMAC interface {
i()
Sha1ToString(data string) string
Sha1ToBase64String(data string) string
Sha256ToString(data string) string
Sha256ToBase64String(data string) string
}
type hmac struct {
secret string
}
func New(secret string) HMAC {
return &hmac{secret: secret}
}
func (m *hmac) i() {}
func (m *hmac) Sha256ToString(data string) string {
h := baseHmac.New(sha256.New, []byte(m.secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
func (m *hmac) Sha256ToBase64String(data string) string {
h := baseHmac.New(sha256.New, []byte(m.secret))
h.Write([]byte(data))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func (m *hmac) Sha1ToString(data string) string {
h := baseHmac.New(sha1.New, []byte(m.secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
func (m *hmac) Sha1ToBase64String(data string) string {
h := baseHmac.New(sha1.New, []byte(m.secret))
h.Write([]byte(data))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}