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

报告相同问题?

悬赏问题

  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算