I have a table where there are two columns: license & activated.
I am storing the license code, not in plain text but hashed. I am using bcrypt module to generate hash with salt round 10. The problem occurs when I search a license into the database. To search a license, I first generate the hash of the license and then search into the database. It works fine until the server is restarted.
When the server restarts, it generates a different hash string for the same license code. Is there any way to fix this? How can I stop changing the hashing pattern for the same license code everytime the server restarts?
The problem is the salt and the way you are using bcrypt. You are using saltRounds to generate new salt (a random value) hence the hash will always be different. If use a fixed salt value the hash will be the same. See the example below:
const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';
bcrypt.genSalt(saltRounds, function(err, salt) {
console.log('new salt:%s',salt);
bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
// Store hash in your password DB.
console.log('new hash:%s',hash);
});
})
//first time generated values were below, but each run will generate new values:
//salt:$2b$10$X4kv7j5ZcG39WgogSl16au
//hash:$2b$10$X4kv7j5ZcG39WgogSl16aupL0..j8Fmm8Lwgq92uWuM5KyXhE6tpO
//Generate the same hash value as fixed salt value is used
salt = '$2b$10$X4kv7j5ZcG39WgogSl16au'
bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
console.log('same value:%s', hash); //hash:$2b$10$X4kv7j5ZcG39WgogSl16aupL0..j8Fmm8Lwgq92uWuM5KyXhE6tpO
});
// Test comparison
hash='$2b$10$X4kv7j5ZcG39WgogSl16aupL0..j8Fmm8Lwgq92uWuM5KyXhE6tpO' //first hash of myPlaintextPassword
bcrypt.compare(myPlaintextPassword, hash, function(err, res) {
console.log('Test using the correct password/key - should authenticate');
if (res === true) {
console.log('authenticated ');
} else {
console.log('NOT authenticated');
}
});
bcrypt.compare(someOtherPlaintextPassword, hash, function(err, res) {
console.log('Test using an incorrect password/key - should fail authentication');
if (res === true) {
console.log('authenticated');
} else {
console.log('NOT authenticated');
}
});
Perhaps use some other value as the primary key (a licence number) and some encrypted value to indicate if it's a valid licence.
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