Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS - SHA256 Password Encryption

I'm currently learning about encryption and password safety in NodeJS. I'm working with a current example that currently is using PBKDF2, I'd like to switch this out to use SHA256 instead. Is this possible and/or make sense? How would I go about it?

var crypto = require('crypto');  var len = 128;  var iterations = 13000;  module.exports = function (pwd, salt, fn) {   if (3 == arguments.length) {     crypto.pbkdf2(pwd, salt, iterations, len, fn);   } else {     fn = salt;     crypto.randomBytes(len, function(err, salt){       if (err) return fn(err);       salt = salt.toString('base64');       crypto.pbkdf2(pwd, salt, iterations, len, function(err, hash){         if (err) return fn(err);         fn(null, salt, hash);       });     });   } }; 
like image 402
Dustin Avatar asked Oct 07 '13 23:10

Dustin


People also ask

Is Sha-256 secure for passwords?

SHA-256 is one of the most secure hashing functions on the market. The US government requires its agencies to protect certain sensitive information using SHA-256.

Can you encrypt with SHA256?

SHA-256 generates an almost-unique 256-bit (32-byte) signature for a text. See below for the source code. A hash is not 'encryption' – it cannot be decrypted back to the original text (it is a 'one-way' cryptographic function, and is a fixed size for any size of source text).

How do I encrypt a node JS username and password?

While submitting a form, there are some sensitive data (like passwords) that must not be visible to anyone, not even to the database admin. To avoid the sensitive data being visible from anyone, Node. js uses “bcryptjs”. This module enables storing of passwords as hashed passwords instead of plaintext.


1 Answers

If wanted to generate sha256 hashes, then you'd have to drop the iterations and length property as those are specific to pbkdf2. You would then use crypto.createHash() which uses OpenSSL to generate hashes. That being said, the types of hashes you can generate are dependent on the version of OpenSSL that you have installed.

var crypto = require('crypto'); var hash = crypto.createHash('sha256').update(pwd).digest('base64'); 

Your specific implementation might look like this:

var crypto = require('crypto'); module.exports = function(pwd, fn) {   var hash = crypto.createHash('sha256').update(pwd).digest('base64');   fn(null, hash); }; 
like image 75
hexacyanide Avatar answered Sep 21 '22 08:09

hexacyanide