我正试图在我的Go应用程序中编写一个登录函数。我有一个注册函数,它使用bcrypt
来散列密码,因此我可以将其存储在数据库中。
用户已成功注册,并且我在数据库中有哈希密码。在尝试登录时,我尝试将数据库中的散列密码与请求中得到的纯文本密码进行比较。但是,我总是得到这样的错误:
crypto/bcrypt: hashedPassword is not the hash of the given password
我正确地检查了来自数据库的散列密码和来自请求的纯文本密码,并且两者都得到了。使用
err = bcrypt.CompareHashAndPassword([]byte(userInfo.fetchedPassword), []byte(password))
fetchedPassword
是来自数据库的散列密码,password
是我从请求中获得的密码。我总是得到相同的结果。我看过一篇关于这个的帖子,大概是4年前写的,但没有回复。
哈希密码生成:
func hashPassword(password string) ([]byte, error) {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return nil, err
}
return hashedPassword, nil
}
正在从数据库中检索密码:
type info struct {
fetchedEmail string
fetchedPassword string
}
var userInfo info
row := db.QueryRow("SELECT email, password FROM users where email=$1", email)
err := row.Scan(&userInfo.fetchedEmail, &userInfo.fetchedPassword)
fmt.Println(userInfo.fetchedPassword)
if err != nil {
return "", err
}
err = bcrypt.CompareHashAndPassword([]byte(userInfo.fetchedPassword), []byte(password))
if err != nil {
return "", err
}
为了在数据库中设置密码,我只需使用hashedPassword,并使用SQL INSERT
命令将其与用户的其余信息一起插入。
发布于 2020-07-29 21:08:59
返回散列密码的string
,而不是字节。
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
func CheckPassword(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
https://stackoverflow.com/questions/63153987
复制相似问题