Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

crypto.pbkdf2 is asynchronous, how do I treat it as synchronous?

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.

like image 272
Metalskin Avatar asked Jan 09 '13 13:01

Metalskin


1 Answers

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.

like image 57
Kevin Hakanson Avatar answered Sep 19 '22 23:09

Kevin Hakanson