Skip to content

Instantly share code, notes, and snippets.

@soplakanets
Created May 19, 2011 13:20
Show Gist options
  • Save soplakanets/980737 to your computer and use it in GitHub Desktop.
Save soplakanets/980737 to your computer and use it in GitHub Desktop.
Password hashing for node.js
var crypto = require('crypto');
var SaltLength = 9;
function createHash(password) {
var salt = generateSalt(SaltLength);
var hash = md5(password + salt);
return salt + hash;
}
function validateHash(hash, password) {
var salt = hash.substr(0, SaltLength);
var validHash = salt + md5(password + salt);
return hash === validHash;
}
function generateSalt(len) {
var set = '0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ',
setLen = set.length,
salt = '';
for (var i = 0; i < len; i++) {
var p = Math.floor(Math.random() * setLen);
salt += set[p];
}
return salt;
}
function md5(string) {
return crypto.createHash('md5').update(string).digest('hex');
}
module.exports = {
'hash': createHash,
'validate': validateHash
};
@FLYBYME
Copy link

FLYBYME commented Sep 29, 2011

Thanks!

@anselm
Copy link

anselm commented Mar 13, 2012

@soplakanets
Copy link
Author

@anselm: interesting but doubtful blog post

@dak
Copy link

dak commented Sep 14, 2012

var crypto = require('crypto'),
    salt = crypto.randomBytes(128).toString('base64'),
    key;

crypto.pbkdf2( 'password', salt, 10000, 512, function(err, dk) { key = dk; } );

@noahbuscher
Copy link

Thanks so much! This is perfect.

@dkhonig
Copy link

dkhonig commented Oct 16, 2014

Anyone who uses this code is only introducing vulnerabilities into their application. The secure way to hash passwords today is by using pbkdf2 (like dak suggest) and never ever md5!

Learn how to hash password using PBKDF2:
http://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_callback

@ChinaCappuccino
Copy link

Thanks so much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment