Reputation: 593
I've read the documentation many times for the Node crypto module's pbkdf2() function. A question I asked previously was collapsed without much thought - so let me say this: I think that I have a lack of understanding about the callback - but I have read many resources trying to truly understand it - YDKJS Async, MDN, "Learning JavaScript" by O'Reilly.
I have a console.log statement within an else clause in the callback that is logging appropriatey, so I'm certain that the callback is being executed, although my debugging program (in VSCode) isn't halting execution.
I tried two different things, as seen in the code below: one was to declare a variable and change its value to derivedKey.toString('hex') within the else clause, and the other was to return the the derivedKey.toString('hex'). Neither worked.
I tried chaining a then clause, but crypto.pbkdf2 returns void and "property 'then' does not exist on type 'void'".
Here is the written method:
private static async hashPassword(password:string, salt:string):Promise<string> {
var hashedPassword;
const iterations = 50000;
const keylen = 64;
const digest = 'sha512';
const possibleReturnedValue = await crypto.pbkdf2(password, salt, iterations, keylen, digest, (err, derivedKey) => {
if (err) {throw err;}
else {
console.log(derivedKey.toString('hex'));
console.log("Hey now");
hashedPassword = derivedKey.toString('hex');
return derivedKey.toString('hex');
}
})
return hashedPassword;
}
What it really comes down to is this: I don't know how to get the derivedKey.toString('hex') value out of a function that returns 'void' with the callback.
Upvotes: 3
Views: 3381
Reputation: 141
Your problem is that the crypto.pbkdf2
function is a bit old, and does not work with promises but using callbacks. So in order to use this function in modern asynchronous code it will be necessary to wrap that function in a Promise
object.
The key idea is to call the resolve
and reject
function given by the promise's constructor in the callback.
Refactored to return a promise, your function will look like this:
function hashPassword(password:string, salt:string):Promise<string> {
return new Promise((resolve, reject) => {
const iterations = 50000;
const keylen = 64;
const digest = 'sha512';
crypto.pbkdf2(password, salt, iterations, keylen, digest, (err, key) => {
if (err) {
reject(err);
} else {
resolve(key.toString('hex'));
}
})
});
}
Upvotes: 7