diff --git a/crypto/crypto.go b/crypto/crypto.go index 454c786..e5e2d3e 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -1,17 +1,55 @@ package crypto import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "golang.org/x/crypto/bcrypt" ) +// DefaultCost 最小值=4 最大值=31 默认值=10 +var DefaultCost = 10 + // HashPassword 加密密码 func HashPassword(password string) (string, error) { - bytes, err := bcrypt.GenerateFromPassword([]byte(password), 10) + // Prefix + Cost + Salt + Hashed Text + bytes, err := bcrypt.GenerateFromPassword([]byte(password), DefaultCost) return string(bytes), err } -// CheckPasswordHash 校验密码 -func CheckPasswordHash(password, hash string) bool { +// HashPasswordWithSalt 对密码进行加盐哈希处理 +func HashPasswordWithSalt(password, salt string) (string, error) { + // 将密码和盐组合 + combined := []byte(password + salt) + + // 计算哈希值 + hash := sha256.Sum256(combined) + + // 将哈希值转换为十六进制字符串 + return hex.EncodeToString(hash[:]), nil +} + +// VerifyPassword 验证密码是否正确 +func VerifyPassword(password, hash string) bool { err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) return err == nil } + +// VerifyPasswordWithSalt 验证密码是否正确 +func VerifyPasswordWithSalt(password, salt, hashedPassword string) bool { + // 对输入的密码和盐进行哈希处理 + newHash, _ := HashPasswordWithSalt(password, salt) + // 比较哈希值是否相同 + return newHash == hashedPassword +} + +// GenerateSalt 生成指定长度的盐 +func GenerateSalt(length int) (string, error) { + salt := make([]byte, length) + _, err := rand.Read(salt) + if err != nil { + return "", err + } + return hex.EncodeToString(salt), nil +} diff --git a/crypto/crypto_test.go b/crypto/crypto_test.go index b53215f..89e7949 100644 --- a/crypto/crypto_test.go +++ b/crypto/crypto_test.go @@ -2,9 +2,10 @@ package crypto import ( "fmt" - "github.com/stretchr/testify/assert" "strings" "testing" + + "github.com/stretchr/testify/assert" ) func TestHashPassword(t *testing.T) { @@ -13,13 +14,15 @@ func TestHashPassword(t *testing.T) { fmt.Println(hash) } -func TestCheckPasswordHash(t *testing.T) { +func TestVerifyPassword(t *testing.T) { text := "123456" + + // Prefix + Cost + Salt + Hashed Text hash3 := "$2a$10$ygWrRwHCzg2GUpz0UK40kuWAGva121VkScpcdMNsDCih2U/bL2qYy" - bMatched := CheckPasswordHash(text, hash3) + bMatched := VerifyPassword(text, hash3) assert.True(t, bMatched) - bMatched = CheckPasswordHash(text, hash3) + bMatched = VerifyPassword(text, hash3) assert.True(t, bMatched) } diff --git a/tag.bat b/tag.bat index 4e4f10f..1775977 100644 --- a/tag.bat +++ b/tag.bat @@ -1,4 +1,4 @@ -git tag v1.1.15 +git tag v1.1.16 git tag bank_card/v1.1.4 git tag geoip/v1.1.4