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 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决