title: Password Hashing in Node.js
body: <p>This is my current code for password hashing and saving to the database:</p>
  
  <pre><code>var config = {
    hashBytes: 64,
    saltBytes: 64,
    iterations: 8000
  };
  
  crypto.randomBytes(config.saltBytes, function(err, salt) {
  
    crypto.pbkdf2(password, salt, config.iterations, config.hashBytes,
        function(err, hash) {
  
            var combined = new Buffer(hash.length + salt.length + 8);
  
            combined.writeUInt32BE(salt.length, 0, true);
            combined.writeUInt32BE(config.iterations, 4, true);
            salt.copy(combined, 8);
            hash.copy(combined, salt.length + 8);
  
            callback(combined);
        });
    });
  </code></pre>
  
  <p>The goal of the code was to save salt together with the hash to one field in database. Is this acceptable way to store a password/salt in the same field in the database? I've found this algorithm long time ago and now so I'm not sure do I understand this well.</p>
  
  <p>As I understand, first we create a buffer which has enough space to store hash, salt, number of iterations and salt length (not sure why are we adding 8 here):</p>
  
  <pre><code>var combined = new Buffer(hash.length + salt.length + 8); 
  </code></pre>
  
  <p>Then we save salt length byte to position 0:</p>
  
  <pre><code>combined.writeUInt32BE(salt.length, 0, true);
  </code></pre>
  
  <p>We save iterations position 4 (why 4?):</p>
  
  <pre><code>combined.writeUInt32BE(config.iterations, 4, true);
  </code></pre>
  
  <p>We save salt to position 8:</p>
  
  <pre><code>salt.copy(combined, 8);
  </code></pre>
  
  <p>We save hash to position which is the length of salt plus the size where we saved iterations and salt length:</p>
  
  <pre><code>hash.copy(combined, salt.length + 8);
  </code></pre>