-2

I wrote a node.js code using crypto.pbkdf2, but variable hash at (2) does not store the value properly so that return value is not normal.

My console log was shown below:

(2) undefined (1) cee2060d38864290804fb3f3446d98c3bf01f9dd0faf937aa25d9ee4a4d9b9f22cdddea532d8a3f7db482cbc8437d8073b1754772561bcb3032990895d29eb06edf2f7539cb04add7502e5d99fb3f58bd6a86cfb529128a2e486b5c21fe755761771ef8181c25b2b5ce8de4a035f169657ea8887505911f0ad8cd265fb7805c3314baabaf3dc7980f131f9a1c4084db47b6d4fff1b52331e23757f9e327efa74a0d9ec4afbade9bd4829abb24c0f5ab713616153f297a6f164f453d6cde409e293b189d13e0a12b64d1f5c6019d8dd10e3d00217ee42b126f99c76a3dfda263bc044a07b2d8f0a2d1d481022d4dc3365149e725c0e6433c53ed207fd3c691d31

My code is here:

function isPasswordCorrect(savedHash, savedSalt, savedIterations, passwordAttempt) {
    var hash;
    crypto.pbkdf2(passwordAttempt, savedSalt, savedIterations, 256, 'sha256', function (err, key) {
        if (err) throw err;
        hash = key.toString('hex');
        console.log("(1) "+hash);
    });
    console.log("(2) "+hash);
    return savedHash == hash;
}

Would you help me solve this problem?

zaph
  • 111,848
  • 21
  • 189
  • 228
  • Did you expect a 256-byte result from `crypto.pbkdf2`? In general that is longer than usual. It is also a good idea to save the salt and iteration count with the hash. – zaph Jun 20 '17 at 01:00
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – peteb Jun 20 '17 at 01:09
  • Yep, noting "(2)" printed before "(1)". – zaph Jun 20 '17 at 01:11

1 Answers1

3

Crypto.pbkdf2 is an async function thus when 2 logs it is before the callback for Cypto.pbkdf2 has executed and set the variable hash to the hash. This is the expected outcome for the code you posted.

function isPasswordCorrect(savedHash, savedSalt, savedIterations, 
passwordAttempt) {
var hash;
crypto.pbkdf2(passwordAttempt, savedSalt, savedIterations, 256, 'sha256', function (err, key) {
     /// this is the callback, it happens when cypto is done, it is non blocking
    if (err) throw err;
    hash = key.toString('hex');
    console.log("(1) "+hash);
});
// this happens before the callback... 
console.log("(2) "+hash);
return savedHash == hash;
}  

You're going to want to pass a callback within the arguments of your isPasswordCorrect function to take the value returned to crypto.pbkdf2

function isPasswordCorrect(savedHash, savedSalt, savedIterations, 
  passwordAttempt, callback) {
    crypto.pbkdf2(passwordAttempt, savedSalt, savedIterations, 
    256,'sha256', callback);
}

In the callback you will handle err and key.

Shadowfool
  • 965
  • 11
  • 21