use*_*063 2 javascript java authentication passwords node.js
我是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);
});
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
执行代码时遇到以下错误
passwordinDB : StAxL1r3bb/5k/6D6+BulwxhXFs=
saltinDB : FOhs8crXyO8=
[Error: Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue]
Run Code Online (Sandbox Code Playgroud)
它无法找到盐的轮数或代码中可能丢失的任何其他轮数,如何克服此错误。
谢谢..!!
这是数据类型的问题!
saltRounds应该是 类型Number。.env如果您使用文件来存储值,则可能会出现问题- 所有值都以Strings 形式存储在 env 文件中。
在这种情况下,要么在代码中分配值const saltRounds = 10,要么将 env 变量强制为 number const saltRounds = Number(process.env.BCRYPT_COST);。
更好的是,由于该值不会改变,因此可以直接传递给哈希函数
const passwordHash = await bcrypt.hash(password, 10);
| 归档时间: |
|
| 查看次数: |
18368 次 |
| 最近记录: |