Golang有人可以解释为什么哈希比较失败
I am trying to develop a user login system, in order for that I am testing the bcrypt function of golang. But I faced some funny situation.
My bcrypt learning material is come from this, the code works well https://medium.com/@jcox250/password-hash-salt-using-golang-b041dc94cb72
But when I wrote my own code, it keep fail in comparison.
package main
import (
"log"
"golang.org/x/crypto/bcrypt"
)
func main() {
hash1, _ := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.MinCost)
hash2, _ := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.MinCost)
err := bcrypt.CompareHashAndPassword(hash1, hash2)
if err != nil {
log.Println(err)
} else {
log.Println("success")
}
}
Since the string for hashing is the same "123456", I except the output of my code should be success
, but the outcome is crypto/bcrypt: hashedPassword is not the hash of the given password
.
Can someone explain this and guide me.
我正在尝试开发用户登录系统,以便测试golang的bcrypt功能。 但是我遇到了一些有趣的情况。 p>
我的bcrypt学习材料就是以此为基础的,代码运行得很好 https://medium.com/@jcox250/password-hash-salt-using-golang-b041dc94cb72 p>
但是当我编写自己的代码时,它在比较中总是失败。 p>
包main
import(
“ log”
“ golang.org/x/crypto/bcrypt"
)
func main(){
hash1,_:= bcrypt.GenerateFromPassword([] byte(“ 123456”),bcrypt.MinCost)
hash2,_ := bcrypt.GenerateFromPassword([] byte(“ 123456”),bcrypt.MinCost)
错误:= bcrypt.CompareHashAndPassword(hash1,hash2)
如果错误!= nil {
log.Println( err)
} else {
log.Println(“ success”)
}
}
code> pre>
因为用于哈希的字符串与“ 123456”相同 ”,除了我的代码输出应为 success code>之外,但结果为 crypto / bcrypt:hashedPassword不是 code>。 p>
有人可以解释一下并指导我。 p>
div>
The documentation for the function you are using says it compares a hash to a plaintext password - not a hash to a hash:
CompareHashAndPassword compares a bcrypt hashed password with its possible plaintext equivalent. Returns nil on success, or an error on failure.
If you were to print or compare each of the generated hashes, they would not match exactly either (that's kind of the point). But you should be able to use the CompareHashAndPassword
function to check if a password was used to generate the given hash.
Try this:
err := bcrypt.CompareHashAndPassword(hash1, []byte("123456"))
if err != nil {
log.Println(err)
} else {
log.Println("success")
}