'use strict';
var crypto = require('crypto');


//current June 22 2016 best practice is
//a 128 byte random per user salt
//512 hash
//100000 iterations (takes about 1 second per to generate)
var LEN = 512;  
var SALT_LEN = 128;  
var ITERATIONS = 100000;  
var DIGEST = 'sha512';

exports.hashPassword = function (password, salt, callback) {  
  var len = LEN / 2;

  if (3 === arguments.length) {
    crypto.pbkdf2(password, salt, ITERATIONS, len, DIGEST, function(err, derivedKey) {
      if (err) {
        return callback(err);
      }

      return callback(null, derivedKey.toString('hex'));
    });
  } else {
    callback = salt;
    crypto.randomBytes(SALT_LEN / 2, function(err, salt) {
      if (err) {
        return callback(err);
      }

      salt = salt.toString('hex');
      crypto.pbkdf2(password, salt, ITERATIONS, len, DIGEST, function(err, derivedKey) {
        if (err) {
          return callback(err);
        }

        callback(null, derivedKey.toString('hex'), salt);
      });
    });
  }
}