添加测试文件
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
package bcryptx
|
||||
|
||||
import "golang.org/x/crypto/bcrypt"
|
||||
|
||||
// HashPassword 使用 bcrypt 算法对密码进行哈希处理
|
||||
func HashPassword(password string) (string, error) {
|
||||
// 第二个参数是 cost 值,代表计算强度
|
||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(bytes), nil
|
||||
}
|
||||
|
||||
// CheckPasswordHash 检查密码是否与哈希值匹配
|
||||
func CheckPasswordHash(password, hash string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package bcryptx_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"code.yun.ink/pkg/encryptx/bcryptx"
|
||||
)
|
||||
|
||||
func TestDecryptBcrypt(t *testing.T) {
|
||||
str, err := bcryptx.HashPassword("password")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
t.Log(str)
|
||||
if bcryptx.CheckPasswordHash("password", str) {
|
||||
t.Log("ok")
|
||||
} else {
|
||||
t.Error("error")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user