2017-06-20 5 views
-2

Ich schrieb einen node.js Code mit crypto.pbkdf2, aber die Variable hash bei (2) speichert den Wert nicht richtig, so dass der Rückgabewert nicht normal ist.Node.js crypto.pbkdf2

Mein Konsolenprotokoll wurde unten gezeigt:

(2) Nicht spezifiziert (1) cee2060d38864290804fb3f3446d98c3bf01f9dd0faf937aa25d9ee4a4d9b9f22cdddea532d8a3f7db482cbc8437d8073b1754772561bcb3032990895d29eb06edf2f7539cb04add7502e5d99fb3f58bd6a86cfb529128a2e486b5c21fe755761771ef8181c25b2b5ce8de4a035f169657ea8887505911f0ad8cd265fb7805c3314baabaf3dc7980f131f9a1c4084db47b6d4fff1b52331e23757f9e327efa74a0d9ec4afbade9bd4829abb24c0f5ab713616153f297a6f164f453d6cde409e293b189d13e0a12b64d1f5c6019d8dd10e3d00217ee42b126f99c76a3dfda263bc044a07b2d8f0a2d1d481022d4dc3365149e725c0e6433c53ed207fd3c691d31

hier

ist mein Code:

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; 
} 

Würden Sie mir helfen, dieses Problem zu lösen?

+0

Haben Sie ein 256-Byte-Ergebnis von 'crypto.pbkdf2' erwartet? Im Allgemeinen ist das länger als gewöhnlich. Es ist auch eine gute Idee, die Salz- und Iterationszählung mit dem Hash zu speichern. – zaph

+1

Mögliches Duplikat von [Wie gebe ich die Antwort von einem asynchronen Anruf zurück?] (Https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – peteb

+0

Ja, notieren "(2)" vor "(1)" gedruckt. – zaph

Antwort

0

Crypto.pbkdf2 ist eine asynchrone Funktion, also wenn 2 Logs es ist, bevor der Callback für Cypto.pbkdf2 ausgeführt und den Variablen-Hash auf den Hash gesetzt hat. Dies ist das erwartete Ergebnis für den von Ihnen geposteten Code.

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; 
} 

Sie gehen zu wollen, einen Rückruf innerhalb der Argumente Ihrer isPasswordCorrect Funktion zu übergeben, den Wert zu übernehmen zurück

function isPasswordCorrect(savedHash, savedSalt, savedIterations, 
    passwordAttempt, callback) { 
    crypto.pbkdf2(passwordAttempt, savedSalt, savedIterations, 
    256,'sha256', callback); 
} 

Im Rückruf crypto.pbkdf2 Sie err und Schlüssel behandelt.