在做注册时应用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后胜利了
功败垂成,最初试了一下就用最后的代码,加密和解密在两个文件也是能够的
发表回复