Search code examples
node.jsasync-awaitpbkdf2

"Error: No callback provided to pbkdf2" when using async await


I want to write an async function for pbkdf2 password hash using crypto module in Nodejs. While the randomBytes function works fine, I get the following erroron running pbkdf2 with await: "Error: No callback provided to pbkdf2".

I know a workaround could be using pbkdf2Sync() but I can't understand why the async version does not work or is it correct to await on a sync function?

Node v 8.10.0

async function hashPassword(password){
	let salt;
	let hash;
	let pass;
	try{
		salt = await Crypto.randomBytes(Config.SALT_BYTES);
		hash = await Crypto.pbkdf2(password, salt, Config.ITERATIONS, Config.HASH_BYTES, 'sha512');
		pass = salt+hash;
		return pass;
	}
	catch(err){
		console.log('ERR: ', err);
	}
}


Solution

  • One solution would be to wrap the method in a promise. Any method that requires a callback can be converted into one that supports async/await in this way.

    function pbkdf2Async(password, salt, iterations, keylen, digest) {
        return new Promise( (res, rej) => {
            crypto.pbkdf2(password, salt, iterations, keylen, digest, (err, key) => {
                err ? rej(err) : res(key);
            });
        });
    }