title: How do I decrypt password using crypto hash and salt with my function in mongoose?
body: <p>I have a set of server side functions that 1. </p>
  
  <ol>
  <li>Generates a random salt </li>
  <li>Uses password and salt to create a hash</li>
  <li><p>Invokes the second function to create hashed password that is returned</p>
  
  <pre><code>var sha512 = function(password, salt){
      var hash = crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */
      hash.update(password);
      var value = hash.digest('hex');
      return {
          salt:salt,
          passwordHash:value
      };
  };
  
  
  //--------------Function to hash password
  function saltHashPassword(userpassword) {
      var salt = genRandomString(16); /** Gives us salt of length 16 */
      var passwordData = sha512(userpassword, salt);
      console.log('UserPassword = '+userpassword);
      console.log('Passwordhash = '+passwordData.passwordHash);
      console.log('\nSalt = '+passwordData.salt);
      return passwordData;
  }
  //----------------------
  // Function to generate salt
  var genRandomString = function(length){
      return crypto.randomBytes(Math.ceil(length/2))
          .toString('hex') /** convert to hexadecimal format */
          .slice(0,length);   /** return required number of characters */
  };
  </code></pre></li>
  </ol>
  
  <p>Whenever I get a username and password in the sign up page, I can call saltHashPassword(passwordinstring) and get a hash and a salt. I then save this to the user document in the mongoose schema.</p>
  
  <p><strong>How do I decrypt when the user is trying to login?</strong></p>
  
  <p>This is a method I'm currently writing in the User schema, user.js. I'm stuck with how get the salt stored for the email provided.</p>
  
  <pre><code>// this authenticates the user against the database
  UserSchema.statics.authenticate = function(email, password, callback){
      User.findOne({email: email})
          .exec(function(error, user){
              if(error){
                  return callback(error);
              }else if(!user){
                  var err = new Error("User not found");
                  err.status = 401;
                  return callback(err);
              }
              // if we reach this part of the code, then there is a valid username
              // I could call sha512(password, salt) and get the hash and then
              // match the two calculated hashed passwords. But how do 
              // I query the salt within a mongo query?
              // every user has email, hashed_password, salt fields in its document
  
          });
  };
  </code></pre>