Testing Bcrypt

This week I ran into an issue with a Node servers lab that had an encrypted component. The way the lab had originally been set up, the encryption used the Node crypto module, which it then decrypted in the test suite to confirm that the result matched the input. However, the lab had then been updated to use the bcrypt module, which I’m very familiar with from Ruby on Rails.

The problem I ran into was that after updating to bcrypt, someone had updated the test suite to include bcrypt methods instead of crypto, but it looks like that had not been merged into the Master. So when I had forked and cloned the Master, I got the updated version of the lab, but not the most up to date version of the test-suite. So even though I was pretty confident that I had set up my bcrypt hash correctly (see below)  the tests weren’t passing.

let data = JSON.stringify(messages);

bcrypt.hash(data, 10, (error, hashed) => {
     response.end(hashed);
});

Because I did not yet realize there was a version I could copy from github, I googled how to test a bcrypt hash and found a bunch of snarky responses saying you can’t. Which isn’t exactly true. After some investigating on the github repository and a little customization on my part I ended up with the following test (within a larger request), which worked like a charm:

bcrypt.compare(
     ‘[{“id”:1,”message”:”This is a test message.”}],
     response.text,
(error, response) => {
          response.should.eql(true);
          done();
}
);

Behold, the magic of the compare method.

Leave a comment