我使用crypto.pbkdf2编写了一个node.js代码,但是(2)中的变量hash
没有正确存储该值,因此返回值不正常。
我的控制台日志如下所示:
(2)undefined(1) cee2060d38864290804fb3f3446d98c3bf01f9dd0faf937aa25d9ee4a4d9b9f22cdddea532d8a3f7db482cbc8437d8073b1754772561bcb3032990895d29eb06edf2f7539cb04add7502e5d99fb3f58bd6a86cfb529128a2e486b5c21fe755761771ef8181c25b2b5ce8de4a035f169657ea8887505911f0ad8cd265fb7805c3314baabaf3dc7980f131f9a1c4084db47b6d4fff1b52331e23757f9e327efa74a0d9ec4afbade9bd4829abb24c0f5ab713616153f297a6f164f453d6cde409e293b189d13e0a12b64d1f5c6019d8dd10e3d00217ee42b126f99c76a3dfda263bc044a07b2d8f0a2d1d481022d4dc3365149e725c0e6433c53ed207fd3c691d31
我的代码在这里:
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;
}
你能帮我解决这个问题吗?
答案 0 :(得分:0)
Crypto.pbkdf2是一个异步函数,因此当2个日志记录在Cypto.pbkdf2的回调执行之前,并将变量哈希设置为哈希值。这是您发布的代码的预期结果。
D:\git\Monitor\WebContent
您将要在isPasswordCorrect函数的参数内传递回调,以获取返回给crypto.pbkdf2的值
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;
}
在回调中,您将处理错误和密钥。