• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

koa2+mysql+bcrypt.compareSync一直返回false

武飞扬头像
雨顺518
帮助1

在做注册时使用bcrypt加密,将加密后的密码存到数据库,然后登录的时候,通过bcrypt.compareSync对比用户输入的密码和数据库的密码,结果竟然一直返回false
之前的代码为

注册:
User.init(
    userpwd: {
      type: Sequelize.STRING,
      set(val) {
        const salt = bcrypt.genSaltSync(10)
        const psw = bcrypt.hashSync(val, salt)
        this.setDataValue('userpwd', psw)
        const correct = bcrypt.compareSync(val, psw)
        console.log(val, psw, correct, 'correct000')
      },
    },
    
  },
  {
    sequelize,
    tableName: 'users',
  }
)

登录:

const { user_name, userpwd } = ctx.request.body

const haveUser = await User.findOne({
  where: {
    user_name,
  },
})
if (haveUser) {
const isPass = bcrypt.compareSync(userpwd, haveUser.userpwd)
console.log(isPass) // 这里一直是false
if (isPass) {
  // 获取token
  let token = getToken(haveUser.uid, havePhone.user_name)
  ctx.body = {
    code: 10000,
    data: {
      token,
    },
  }
} else {
  throw new PasswordError()
}
}
学新通

一直不行都返回false,折腾了好久到快怀疑人生了,后来觉得加密和解密不是在同一个文件,所以改代码

class User extends Model {
  static async checkPassword(user_name, userpwd) {
    const user = await this.findOne({
      where: {
        user_name,
      },
    })
    if (!user) {
      throw new NotExsitError()
    }
    // 验证密码是否一致
    const correct = bcrypt.compareSync(userpwd, user.userpwd)
    console.log(userpwd, user.userpwd, correct, 'correct')
    if (!correct) {
      throw new PasswordError()
    }
    return user
  }
}

User.init(
      type: Sequelize.STRING,
      set(val) {
        const salt = bcrypt.genSaltSync(10)
        const psw = bcrypt.hashSync(val, salt)
        this.setDataValue('userpwd', psw)
        const correct = bcrypt.compareSync(val, psw)
        console.log(val, psw, correct, 'correct000')
      },
    },
  },
  {
    sequelize,
    tableName: 'users',
  }
)

然后登录时
const { user_name, userpwd } = ctx.request.body
const haveUser = await User.checkPassword(user_name, userpwd)

学新通

怀着激动的心情,以为会返个true给我,结果checkPassword方法里的console.log打出来还是false,百度查了好久也没有找到一个有用的,后来想着实在不行算了,密码就用原文吧不加密了,刚开始做node项目好多不太熟,后来想着在注册的时候把密码和加密后的打印出来,然后登录的时候再把这两个打印出来对比一下,果然发现了猫腻

学新通
注册时和登录时加密串不一样,但是前半部分是一样的,所以想到了数据库存的时候是不是给截取了,看了一下果然是的密码长度为32太短了

学新通
所以改成128后成功了
学新通

大功告成,最后试了一下就用最初的代码,加密和解密在两个文件也是可以的

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggaffj
系列文章
更多 icon
同类精品
更多 icon
继续加载