dongzuan4491 2019-05-02 11:14
浏览 104
已采纳

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.

  • 写回答

1条回答 默认 最新

  • doutan6286 2019-05-02 12:48
    关注

    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")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料