Pablo
Pablo

Reputation: 69

Node.js password hash and salt questions

I'm implementing an authenticated web app and I've some questions about username and password storage.

There is no possibility of implementing any TFA method and I need some expert advice about the way I'm saving in the database the hashed password and the salt.

These are my JS functions to generate the salt and the way I hash the password:

createSalt = function() {
var len = 30;
return crypto.randomBytes(Math.ceil(len * 3 / 4))
    .toString('base64') // convert to base64 format
    .slice(0, len) // return required number of characters
    .replace(/\+/g, '0') // replace '+' with '0'
    .replace(/\//g, '0'); // replace '/' with '0'
}

hashPassword = function(password, salt) {
    var hash = crypto.createHash('sha256');
    hash.update(password || "");
    hash.update(salt || "");
    return hash.digest('hex');
}

Any comment or improvement?

Thanks in advice.

Upvotes: 0

Views: 827

Answers (1)

Sebastian Hildebrandt
Sebastian Hildebrandt

Reputation: 2771

As nodes crypto provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) implementation, you can do it like that (2 liner):

let saltlength = 32;
let keylength = 128;

let salt = crypto.randomBytes(saltlength).toString('hex');
let key = crypto.pbkdf2Sync(password, salt, 1000, keylength, 'sha512').toString('hex');

where 1000 is number of iterations... As toString(hex)doubles the length of the string, here you get a salt length of 64 and a key length of 256 ... adapt for your needs. I personally like to use longer salt length (128) and longer key length (512)

toString('base64') - the one you used saves a little bit of space ... but needs then a little "afterwork". But anyway, I like your approach.

Upvotes: 1

Related Questions