BCrypt比较两个哈希值不相等。

huangapple go评论77阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2015年11月13日 09:01:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/33684259.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定