卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34148本站已运行391

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

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

问题内容

我正在制定一条对用户进行身份验证的路线,当我创建用户时,我将密码保存为哈希值,并在身份验证中创建了此函数来使用 crypto/bcrypt 库验证密码:

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,但出现此错误


正确答案


// 比较哈希值 $2a$10$gripzjzty3f0kgujs5egzevfvn1flwkkwl3isa30onhlo2vuhkyfa $2a$10$gripzjzty3f0kgujs5egzevfvn1flwkkwl3isa30onhlo2vuhkyfa

此处的日志意味着散列密码传递给 (*user).validatepasswordbcrypt.comparehashandpassword 比较两个散列密码。这是不正确的,bcrypt.comparehashandpassword 应该比较哈希密码和纯密码。

p.s. 这样做 password: string(hash) 是个坏主意。 语言规范允许这样做,但生成的字符串可能包含无效的 unicode 代码点,并且其他软件可能无法接受或正确处理它。例如,无效的代码点会被 postgresql 拒绝。以下演示将出现错误并显示消息:error:编码“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: %vn", 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)
    }
}
卓越飞翔博客
上一篇: golang 使用 functools.partial 或类似的方法来完成包装其他函数
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏