Search code examples
javascriptnode.jsecmascript-6es6-promise

Cryptographer TypeError: First argument must be a string


So I'm trying to create a Unit test for some pincode/password hashing. I came across this error earlier aswell, but then I was able to solve it with a simple .toString(), but now that doesn't seem to work.

This is some of my code related to the methods:

pin.model.spec.js:

let pin = Math.floor(1000 + Math.random() * 9000);
let hash = await Pincode.getHashedPincode(pin.toString(), salt);

crypto.js:

function getPasswordHash(password, salt) {
  return new Promise((resolve, reject) => {
    crypto.pbkdf2(password, new Buffer(salt, 'hex'), iterations, keyLength, 'SHA1', (err, result) => {
      if (err) {
        return reject(err);
      }
      return resolve(result.toString('hex'));
    });
  });
}

Dont worry about the inconsistant method names, between them there is a method called getHashedPincode the does nothing else but calls getPasswordHash just for naming conventions. The vars iterations and keyLength come from a constants file. So that is not the issue either.

I hope someone can lead me to the right direction

EDIT:

This is the whole getHashPincode:

Pincode.getHashedPincode = async (pincode, salt) => {
  return cryptographer.getPasswordHash(pincode, salt);
};

Solution

  • There is nothing wrong with pin.toString().

    What's causing the error is new Buffer(salt, 'hex'), since you specified an encoding (hex) then the first argument (salt) must be a string. salt.toString() should do the trick