Question

I was thinking of using bcrypt (npm install bcrypt) to hash passwords for my node.js application. I decided to make two small scripts as proofs of concept, basically following the instructions from node.bcrypt.js:

createHash.js

var bcrypt = require('bcrypt'),
    password = process.argv[2];

bcrypt.hash(password, 10, function(err, hash) {
    console.log(hash);
});

checkPassword.js

var bcrypt = require('bcrypt'),
    hash = process.argv[2],
    password = process.argv[3];

bcrypt.compare(password, hash, function(err, res) {
    console.log(res);
});

Trying them out looks like this:

$ node createHash.js bacon
$2a$10$Iy8XG2C5.OMysi2S9UK2fu3omruWE4nXnhSKRD2fmNnImEAqayJs2
$ node checkPassword.js $2a$10$Iy8XG2C5.OMysi2S9UK2fu3omruWE4nXnhSKRD2fmNnImEAqayJs2 bacon
false

Since I used the same password for both calls (bacon), I expected that second call to return true, not false. Can anyone explain why this doesn't behave as expected?

Was it helpful?

Solution

This is because some shells interpret the $ in your hash as special characters referring to variables.

To get around this, surround your hash with quotes:

bash-3.2$ node createHash.js bacon
$2a$10$i.RiIPW5wSSooTHJI6Sl6usKdx94uAmSUZ8489.os9OKLWGcuO6tm
bash-3.2$ node checkPassword.js $2a$10$i.RiIPW5wSSooTHJI6Sl6usKdx94uAmSUZ8489.os9OKLWGcuO6tm bacon
false
bash-3.2$ node checkPassword.js '$2a$10$i.RiIPW5wSSooTHJI6Sl6usKdx94uAmSUZ8489.os9OKLWGcuO6tm' bacon
true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top