feat: crypto

This commit is contained in:
Bobo
2025-04-10 15:15:46 +08:00
parent 2ab920982a
commit 713975e7f1
3 changed files with 49 additions and 8 deletions

View File

@@ -1,17 +1,55 @@
package crypto package crypto
import ( import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
// DefaultCost 最小值=4 最大值=31 默认值=10
var DefaultCost = 10
// HashPassword 加密密码 // HashPassword 加密密码
func HashPassword(password string) (string, error) { 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 return string(bytes), err
} }
// CheckPasswordHash 校验密码 // HashPasswordWithSalt 对密码进行加盐哈希处理
func CheckPasswordHash(password, hash string) bool { 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)) err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil 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
}

View File

@@ -2,9 +2,10 @@ package crypto
import ( import (
"fmt" "fmt"
"github.com/stretchr/testify/assert"
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestHashPassword(t *testing.T) { func TestHashPassword(t *testing.T) {
@@ -13,13 +14,15 @@ func TestHashPassword(t *testing.T) {
fmt.Println(hash) fmt.Println(hash)
} }
func TestCheckPasswordHash(t *testing.T) { func TestVerifyPassword(t *testing.T) {
text := "123456" text := "123456"
// Prefix + Cost + Salt + Hashed Text
hash3 := "$2a$10$ygWrRwHCzg2GUpz0UK40kuWAGva121VkScpcdMNsDCih2U/bL2qYy" hash3 := "$2a$10$ygWrRwHCzg2GUpz0UK40kuWAGva121VkScpcdMNsDCih2U/bL2qYy"
bMatched := CheckPasswordHash(text, hash3) bMatched := VerifyPassword(text, hash3)
assert.True(t, bMatched) assert.True(t, bMatched)
bMatched = CheckPasswordHash(text, hash3) bMatched = VerifyPassword(text, hash3)
assert.True(t, bMatched) assert.True(t, bMatched)
} }

View File

@@ -1,4 +1,4 @@
git tag v1.1.15 git tag v1.1.16
git tag bank_card/v1.1.4 git tag bank_card/v1.1.4
git tag geoip/v1.1.4 git tag geoip/v1.1.4