Storing passwords with Node.js and MongoDB

Use this: https://github.com/ncb000gt/node.bcrypt.js/

bcrypt is one of just a few algorithms focused on this use case. You should never be able to decrypt your passwords, only verify that a user-entered cleartext password matches the stored/encrypted hash.

bcrypt is very straightforward to use. Here is a snippet from my Mongoose User schema (in CoffeeScript). Be sure to use the async functions as bycrypt is slow (on purpose).

class User extends SharedUser
  defaults: _.extend {domainId: null}, SharedUser::defaults

  #Irrelevant bits trimmed...

  password: (cleartext, confirm, callback) ->
    errorInfo = new errors.InvalidData()
    if cleartext != confirm
      errorInfo.message = 'please type the same password twice'
      errorInfo.errors.confirmPassword = 'must match the password'
      return callback errorInfo
    message = min4 cleartext
    if message
      errorInfo.message = message
      errorInfo.errors.password = message
      return callback errorInfo
    self = this
    bcrypt.gen_salt 10, (error, salt)->
      if error
        errorInfo = new errors.InternalError error.message
        return callback errorInfo
      bcrypt.encrypt cleartext, salt, (error, hash)->
        if error
          errorInfo = new errors.InternalError error.message
          return callback errorInfo
        self.attributes.bcryptedPassword = hash
        return callback()

  verifyPassword: (cleartext, callback) ->
    bcrypt.compare cleartext, @attributes.bcryptedPassword, (error, result)->
      if error
        return callback(new errors.InternalError(error.message))
      callback null, result

Also, read this article, which should convince you that bcrypt is a good choice and help you avoid becoming "well and truly effed".


This is the best example I've come across to date, uses node.bcrypt.js http://devsmash.com/blog/password-authentication-with-mongoose-and-bcrypt