hash - 加密/bcrypt : hashedPassword is not the hash of the given password

标签 hash go bcrypt

我加密用户的密码并保存到数据库。然后用户登录,比较散列密码和普通密码,我得到 crypto/bcrypt: hashedPassword is not the hash of the given password 错误。怎么了?

func encryptPassword(password string) (string, error) {
    bytePass := []byte(password)
    hashedPassword, err := bcrypt.GenerateFromPassword(bytePass, bcrypt.DefaultCost)
    if err != nil {
        log.Printf("ERROR:EncryptPassword: %s", err.Error())
    }
    return string(hashedPassword), err
}

func (i *Impl) Register(user User) bool {
    hashedPass, err := encryptPassword(user.Password)
    if err != nil {
        return false
    }

    user.Password = hashedPass

    if err := i.DB.Create(&user).Error; err != nil {
        log.Printf("ERROR:Register: %s", err.Error())
        return false
    }
    return true
}

func (i *Impl) Login(email string, password string) (User, error) {
    var user User
    i.DB.Where("email = ?", email).First(&user)   

    err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
    if err != nil {
        log.Printf("ERROR:Login: %s", err.Error())
        return User{}, err
    }

    return user, err
}

最佳答案

我敢打赌,在将 user.Password 传递给 encryptPassword 之前,您的 Register 函数中的 user.Password 是空的,因此会导致对空密码进行哈希处理就像您提供的一样 ($2a$10$rqHJJTHsxMbtX/5ZjG1mFuWyYbUDW1PLbfwQRN0uChwes38c/0m3e)。

关于hash - 加密/bcrypt : hashedPassword is not the hash of the given password,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35556253/

相关文章:

go - go get 的二进制文件在哪里安装?

go - 在 Go 网络应用程序路由器中检查用户权限的最佳方法

node.js - Nodejs 的 bcrypt 实现中的 "B4c0/\/"是什么?

ruby-on-rails - Rails 3 Devise 停止使用更多加密 "stretches"

python - Python(或 C)中的内存高效字符串到字符串映射

php - PHP 与 C 中的增量哈希

go - 与其他 Go 进程通信

node.js - 我正在尝试使用 nextjs 中的 bcrypt 对管理员密码进行哈希处理以保存到数据库中,但收到错误

algorithm - 使用哈希查找 float 数组的模式

ruby-on-rails - 渲染 json 中的哈希火箭与冒号 :