Skip to content

Instantly share code, notes, and snippets.

@siteslave
Forked from soplakanets/password.js
Created February 4, 2021 15:09
Show Gist options
  • Save siteslave/cdcfd5b939b7794b739e1f0505fa63a9 to your computer and use it in GitHub Desktop.
Save siteslave/cdcfd5b939b7794b739e1f0505fa63a9 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
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment