我是javascript和nodejs的新手,我编写了一段代码来根据数据库中存在的密码和盐对用户进行身份验证,下面是nodejs中的代码,我收到用户代码和密码,然后从数据库检索数据,将数据库中存在的密码和盐与收到的密码进行比较。
DB中存储的salt是通过base64格式生成的。
var Bcrypt = require('bcrypt');
var pg = require('pg');
var usercode = 'tarun';
var clientid='214057357158656';
var password='tarun';
var connectionString = "postgres://dbusername:password@localhost:5432/USCProduction";
console.log('connectin to DB');
var client = new pg.Client(connectionString);
client.connect(function(err) {
if(err) {
console.log(err);
}
var Query ='select password, salt from muser, mclient where usercode='+"'"+usercode+"'"+' and muser.clientid='+clientid+' and muser.clientid=mclient.clientid and mclient.status=1';
console.log('executing query',Query);
client.query(Query, function(err, result) {
if(err){
console.log('Error in executing Query');
client.end();
} else {
console.log(result.rows);
var passinDB=result.rows[0].password;
var saltinDB=result.rows[0].salt;
console.log('passwordinDB : ',passinDB);
console.log('saltinDB : ',saltinDB);
client.end();
Bcrypt.hash(passinDB, saltinDB, function(err, hash) {
if(err) {
return console.error(err);
}
console.log(hash);
Bcrypt.compare(password, hash, function(err, isMatch) {
if(err) {
return console.error(err);
}
console.log('do they match?', isMatch);
});
});
}
});
});
执行代码时遇到以下错误
passwordinDB : StAxL1r3bb/5k/6D6+BulwxhXFs=
saltinDB : FOhs8crXyO8=
[Error: Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue]
它无法找到盐的轮数或代码中可能丢失的任何其他轮数,如何克服此错误。
谢谢你..!!
最佳答案
一种可读的生成方式:
const bcrypt = require("bcryptjs")
const hash = async (text, size) => {
try {
const salt = await bcrypt.genSalt(size);
const hash = await bcrypt.hash(text, salt);
return hash
} catch(error) {
console.log(error)
}
}
关于javascript - Node js 中的身份验证过程中出现无效盐错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38202798/