crypto.go 788 B

12345678910111213141516171819202122232425262728293031
  1. package common
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "golang.org/x/crypto/bcrypt"
  7. )
  8. func GenerateHMACWithKey(key []byte, data string) string {
  9. h := hmac.New(sha256.New, key)
  10. h.Write([]byte(data))
  11. return hex.EncodeToString(h.Sum(nil))
  12. }
  13. func GenerateHMAC(data string) string {
  14. h := hmac.New(sha256.New, []byte(CryptoSecret))
  15. h.Write([]byte(data))
  16. return hex.EncodeToString(h.Sum(nil))
  17. }
  18. func Password2Hash(password string) (string, error) {
  19. passwordBytes := []byte(password)
  20. hashedPassword, err := bcrypt.GenerateFromPassword(passwordBytes, bcrypt.DefaultCost)
  21. return string(hashedPassword), err
  22. }
  23. func ValidatePasswordAndHash(password string, hash string) bool {
  24. err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
  25. return err == nil
  26. }