Am new to javascript and nodejs, I wrote a code to do authentication of the user from the password and salt present in database, Below is the code in nodejs were i receive a usercode and password and i retrieve the data from database and compare the password and salt present in DB with the received password.
The salt stored in DB is generated by base64 format.
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);
});
});
}
});
});
Am facing the following error while ececuting the code
passwordinDB : StAxL1r3bb/5k/6D6+BulwxhXFs=
saltinDB : FOhs8crXyO8=
[Error: Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue]
its unable to find number of rounds of the salt or any other i may be missing in the code ,how to over come this error.
Thank You..!!
It's a data type issue!
saltRounds should be of type Number. The issue can arise if you're using an .env file to store the value - all values are stored as Strings in the env file.
In this case either assign the value in the code const saltRounds = 10 or coerce the env variable to a number const saltRounds = Number(process.env.BCRYPT_COST);.
Better still, since this value is not about to change, it can directly be passed to the hash function
const passwordHash = await bcrypt.hash(password, 10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With