سؤال

I'm using pbkdf2 in node.js for hashing passwords.

My problem is that I'm responding to a request for authentication and I'm in the middle of authenticating if the passed credentials are correct. I'm presuming that pbkdf2 is async as it could potentially take a large amount of time (dependant on the size of the iterations). However moving the remaining authentication logic into a separate method to utilise the callback seems a tad ugly.

Is there a better approach than either using a timer or throwing all the consecutive authentication logic into a separate function? I know most will say that I should use the callback, but in my use case this just doesn't make sense. I cannot continue authentication until I have applied pbkdf2 to the passed password.

هل كانت مفيدة؟

المحلول 2

I can see two solutions for your problem.

First one is to use some library to wrap asynchronous calls. You may try node-sync or node-promise. node-sync is better suited for what you want.

Second solution is to use bcrypt instead of crypto:

var bcrypt = require('bcrypt');
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(password, salt);

bcrypt is a special library for password hashing in node. It's more secure then build-in crypto module and provides some useful methods like hashSync and compareSync.

نصائح أخرى

According to the Node.js crypto docs, there is both an asynchronous and synchronous version of the PBKDF2 function.

crypto.pbkdf2(password, salt, iterations, keylen, callback)

Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive a key of given length from the given password, salt and iterations. The callback gets two arguments (err, derivedKey).

crypto.pbkdf2Sync(password, salt, iterations, keylen)

Synchronous PBKDF2 function. Returns derivedKey or throws error.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top