Bläddra i källkod

密码加密功能

runningwater 8 månader sedan
förälder
incheckning
d9799f3642
2 ändrade filer med 28 tillägg och 1 borttagningar
  1. 1 1
      go.mod
  2. 27 0
      pkg/hash/hash.go

+ 1 - 1
go.mod

@@ -12,6 +12,7 @@ require (
 	github.com/spf13/viper v1.20.1
 	github.com/thedevsaddam/govalidator v1.9.10
 	go.uber.org/zap v1.27.0
+	golang.org/x/crypto v0.37.0
 	gopkg.in/natefinch/lumberjack.v2 v2.2.1
 	gorm.io/driver/mysql v1.5.7
 	gorm.io/driver/sqlite v1.5.7
@@ -56,7 +57,6 @@ require (
 	github.com/ugorji/go/codec v1.2.12 // indirect
 	go.uber.org/multierr v1.10.0 // indirect
 	golang.org/x/arch v0.8.0 // indirect
-	golang.org/x/crypto v0.37.0 // indirect
 	golang.org/x/image v0.23.0 // indirect
 	golang.org/x/net v0.39.0 // indirect
 	golang.org/x/sys v0.32.0 // indirect

+ 27 - 0
pkg/hash/hash.go

@@ -0,0 +1,27 @@
+// Package hash 哈希操作类
+package hash
+
+import (
+	"github.com/runningwater/gohub/pkg/logger"
+	"golang.org/x/crypto/bcrypt"
+)
+
+// BcryptHash bcrypt 哈希, 用于加密密码
+func BcryptHash(password string) string {
+	bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
+	logger.LogIf(err)
+
+	return string(bytes)
+}
+
+// BcryptCheck 检查密码是否匹配
+func BcryptCheck(password, hash string) bool {
+	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
+
+	return err == nil
+}
+
+// BcryptIsHashed 检查密码是否已经被哈希
+func BcryptIsHashed(str string) bool {
+	return len(str) == 60 && str[0] == '$' && str[1] == '2'
+}