英文:
BCrypt comparing two hashes not equal
问题
我有这段代码:
u := models.Users{}
u = u.FindByEmail(login.Email)
password := []byte(login.Password)
hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil {
panic(err)
}
err = bcrypt.CompareHashAndPassword(hashedPassword, []byte(u.Password))
fmt.Println(err)
我最终得到了这个错误:crypto/bcrypt:hashedPassword不是给定密码的哈希值
然而,我之前将我的模型保存为与"admin"相同的哈希值,但当我运行我的应用程序时,它告诉我它们不相等。
英文:
I have this code:
u := models.Users{}
u = u.FindByEmail(login.Email)
password := []byte(login.Password)
hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil {
panic(err)
}
err = bcrypt.CompareHashAndPassword(hashedPassword, []byte(u.Password))
fmt.Println(err)
I end up getting this error: crypto/bcrypt: hashedPassword is not the hash of the given password
However I previously saved my model to have the same hash as "admin", but when I run my application, it tells me it is not equal.
答案1
得分: 5
仔细阅读文档。
CompareHashAndPassword函数用于比较bcrypt哈希密码与可能的明文密码等效项。成功时返回nil,失败时返回错误。
基本上,它的意思是你应该将存储的哈希与明文密码进行比较。
你可能需要:
u := models.Users{}
u = u.FindByEmail(login.Email)
plainPassword := []byte(login.Password)
// 假设u.Password是实际的哈希值,而不是存储的明文密码。
err = bcrypt.CompareHashAndPassword([]byte(u.Password), plainPassword)
fmt.Println(err)
英文:
Re-read the docs carefully.
CompareHashAndPassword compares a bcrypt hashed password with its possible plaintext equivalent. Returns nil on success, or an error on failure.
Basically, it is saying that you should compare the hash you have stored against the plain text password.
you probably want:
u := models.Users{}
u = u.FindByEmail(login.Email)
plainPassword := []byte(login.Password)
// Assumes that u.Password is the actual hash and that you didn't store plain text password.
err = bcrypt.CompareHashAndPassword([]byte(u.Password), plainPassword)
fmt.Println(err)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论