diff --git a/backend/internal/auth/password.go b/backend/internal/auth/password.go new file mode 100644 index 0000000..0664268 --- /dev/null +++ b/backend/internal/auth/password.go @@ -0,0 +1,19 @@ +package auth + +import "golang.org/x/crypto/bcrypt" + +const bcryptCost = 10 + +// HashPassword 使用 bcrypt 对密码进行哈希。 +func HashPassword(password string) (string, error) { + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost) + if err != nil { + return "", err + } + return string(hash), nil +} + +// CheckPassword 校验密码与哈希是否匹配。 +func CheckPassword(hashedPassword, password string) error { + return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) +}