hmac.go 459 B

1234567891011121314151617181920
  1. package codec
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha256"
  5. "encoding/base64"
  6. "io"
  7. )
  8. // Hmac returns HMAC bytes for body with the given key.
  9. func Hmac(key []byte, body string) []byte {
  10. h := hmac.New(sha256.New, key)
  11. io.WriteString(h, body)
  12. return h.Sum(nil)
  13. }
  14. // HmacBase64 returns the base64 encoded string of HMAC for body with the given key.
  15. func HmacBase64(key []byte, body string) string {
  16. return base64.StdEncoding.EncodeToString(Hmac(key, body))
  17. }