hash.go 597 B

123456789101112131415161718192021222324252627
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "golang.org/x/crypto/bcrypt"
  6. )
  7. // BcryptHash 使用 bcrypt 对密码进行加密
  8. func BcryptHash(password string) string {
  9. bytes, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  10. return string(bytes)
  11. }
  12. // BcryptCheck 对比明文密码和数据库的哈希值
  13. func BcryptCheck(password, hash string) bool {
  14. err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
  15. return err == nil
  16. }
  17. func ByteToHex(bt []byte) string {
  18. m := md5.New()
  19. m.Write(bt)
  20. res := hex.EncodeToString(m.Sum(nil))
  21. return res
  22. }