Search code examples
node.jshashcryptographypasswordspbkdf2

Generating and Verifying password hashes in Node.js same as Python's werkzeug


Im moving an app from Python Flask to ExpressJS. I need some help with password hashing and veryfying. In Flask, you can do this:

from werkzeug import generate_password_hash, check_password_hash
pass = 'abcd'
pass_hash = generate_password_hash(pass)
check_password_hash(pass_hash, pass)

And in 4 lines you have a boolean response checking if the password corresponds to the hash.

Now to NodeJS: I know how to create a sha256 hash, a HMAC hash or a cypher, but how would i check the password?


Solution

  • It is also easy to acheve it in node. Use https://github.com/ncb000gt/node.bcrypt.js/ Here is example for koa.

    let bcrypt = require('co-bcrypt');
    
    let storedHash = yield bcrypt.hash("user_password", 10, null);   // to get hash
    
    let isValid = yield bcrypt.compare("user_password", storedHash);  // to compare
    

    In case you would like to use pbkdf2, here is another example.

    const crypto = require('crypto');
    crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, key) => {
      if (err) throw err;
      console.log(key.toString('hex'));  // 'c5e478d...1469e50'
    });
    

    Documentation: https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback