func validateCredentials(attemptedPassword string, actualPasswordHash string) (bool, error) {
    if err := bcrypt.CompareHashAndPassword([]byte(actualPasswordHash), []byte(attemptedPassword)); err != nil {
        fmt.Printf("validateCredentials error is %v", err)
        return false, nil
    }

    return true, nil
}

我写了一个看起来像这样的测试:
func TestAuth_validateCredentials(t *testing.T) {
    var actualPassword = "hello123"
    actualPasswordHash, _ := bcrypt.GenerateFromPassword([]byte(actualPassword), bcrypt.MinCost)
    if valid, err := validateCredentials("username", string(actualPasswordHash)); err != nil {
        t.Error("Unexpted error: ", err)
    } else if valid {
        t.Error("Expected invalid when password is wrong")
    }
}

我不断收到此错误:

validateCredentials错误为crypto / bcrypt:hashedPassword不是
给定密码的哈希值

我在这里做错了什么?

最佳答案

您正在传递"username"而不是actualPassword

if valid, err := validateCredentials(actualPassword, string(actualPasswordHash))

08-26 09:25