title: How to create random-salt-hash with crypto
body: <p>I want to create a salt-hash using node.js crypto lib without having to parse any hardcoded data.</p>
  
  <p>What do I mean with hardcoded?</p>
  
  <pre><code>var salt, hardcodedString = "8397dhdjhjh";
  crypto.createHmac('sha512', hardcodedString).update(salt).digest("base64");
  </code></pre>
  
  <p>Isn't there any other way how I can create a random string without using raw javascript, random functions or hardcoding something?</p>
  
  <p>Regards</p>
  
  <p><strong>UPDATE</strong></p>
  
  <pre><code>var Crypto = require('crypto')
      , mongoose = require('mongoose');
  
  module.exports = mongoose.model('User', new mongoose.Schema({
      username: {
          type: String
          , required: true
          , index: { unique: true, sparse: true }
          , set: toLower
      },
      email: {
          type: String
          , required: true
          , index: { unique: true, sparse: true }
          , set: toLower
      },
      salt: {
          type: String
          , set: generateSalt
      },
      password: {
          type: String
          , set: encodePassword
      }
  }),'Users');
  
  function toLower(string) {
      return string.toLowerCase();
  }
  
  function generateSalt() {
      //return Math.round((new Date().valueOf() * Math.random())) + '';
      Crypto.randomBytes('256', function(err, buf) {
          if (err) throw err;
          return buf;
      });
      // return Crypto.randomBytes('256'); // fails to
  }
  
  function encodePassword(password) {
      return password;
      // TODO: setter has no access to this.salt
      //return Crypto.createHmac('sha512', salt).update(password).digest("base64");
  }
  
  function authenticate(plainPassword) {
      return encodePassword(plainPassword) === this.password;
  }
  </code></pre>