error: crypto/bcrypt: hashedPassword is not the hash of the given password

问题描述 投票:0回答:1

我正在创建一条路线来验证用户,当我创建用户时,我将密码保存为哈希,并且在验证中我创建了这个函数来使用 crypto/bcrypt lib 验证密码:

func (user *User) ValidatePassword(password string) bool {
    err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
    if err != nil {
        println(user.Password, password)
        panic(err)
    }
    return err == nil
}

保存用户时一切正常,但是当我进行身份验证时,密码验证返回此错误:

// hashes compared
$2a$10$gRIPZJZTy3f0KgUjs5eGzeVfVn1fLwkKWL3iSa30OnhLO2VuHkyfa $2a$10$gRIPZJZTy3f0KgUjs5eGzeVfVn1fLwkKWL3iSa30OnhLO2VuHkyfa

// error
http: panic serving 127.0.0.1:62939: crypto/bcrypt: hashedPassword is not the hash of the given password
goroutine 20 [running]:
net/http.(*conn).serve.func1()

我创建一个散列并转换为字符串以保存:

func NewUser(name, email, password string) (*User, error) {
    hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
    if err != nil {
        return nil, err
    }

    return &User{
        ID:       entity.NewID(),
        Name:     name,
        Email:    email,
        Password: string(hash),
    }, nil
}

更多信息: 用户域 用户数据库 用户处理程序

根据文档,我认为我正确使用了

CompareHashAndPassword
,但我得到了这个错误

go bcrypt
1个回答
2
投票

// 比较哈希 $2a$10$gRIPZJZTy3f0KgUjs5eGzeVfVn1fLwkKWL3iSa30OnhLO2VuHkyfa $2a$10$gRIPZJZTy3f0KgUjs5eGzeVfVn1fLwkKWL3iSa30OnhLO2VuHkyfa

这里的日志意味着一个散列密码被传递给

(*User).ValidatePassword
bcrypt.CompareHashAndPassword
比较两个散列密码。这是不正确的,
bcrypt.CompareHashAndPassword
应该比较散列密码和普通密码。


P.S.这样做是个坏主意

Password: string(hash)
语言规范允许这样做,但生成的字符串可能包含无效的 Unicode 代码点,其他软件可能无法接受或正确处理它。例如,PostgreSQL 拒绝无效代码点。以下演示将出现恐慌并显示消息:
ERROR: invalid byte sequence for encoding "UTF8": 0xff (SQLSTATE 22021)
。我认为您可以将
Password
的数据类型更改为
[]byte
并将哈希值作为二进制数据存储在数据库中。

package main

import (
    "context"
    "fmt"
    "os"

    "github.com/jackc/pgx/v5"
)

func main() {
    urlExample := "postgres://postgres:sa123@localhost:5432/taop"
    conn, err := pgx.Connect(context.Background(), urlExample)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
        os.Exit(1)
    }
    defer conn.Close(context.Background())

    _, err = conn.Exec(context.Background(), "CREATE TABLE students(password TEXT)")
    if err != nil {
        panic(err)
    }

    _, err = conn.Exec(context.Background(), "INSERT INTO students(name) VALUES ($1)", string([]byte{0xff, 0xfe, 0xfd}))
    if err != nil {
        panic(err)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.