NodeJS - SHA256 Password Encryption

55,691

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);
};
Share:
55,691
Dustin
Author by

Dustin

Updated on July 10, 2022

Comments

  • Dustin
    Dustin almost 2 years

    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);
          });
        });
      }
    };
    
  • Vadorequest
    Vadorequest over 10 years
    Actually to generate a password hashed in sha256, you have to use digest 'hex': var hash = crypto.createHash('sha256').update(pwd).digest('hex');
  • hexacyanide
    hexacyanide over 10 years
    The hash is still sha256, it's just in a different encoding. The person who asked the question also used base64 as his encoding, therefore, I answered like so.
  • Vadorequest
    Vadorequest over 10 years
    Yeah, it's just that I guess some people don't manage encoding and want a result in basic SHA256 (such as me), I used some time to understand it so I just wanted to help for the nexts :p
  • user740189
    user740189 about 5 years
    Hi, This is nothing but encryption. Can you please let me know how to decrypt?.
  • Elliot Huffman
    Elliot Huffman about 5 years
    Hi @user740189, SHA is a one way algorithm, a hashing algorithm. It is not meant to be reversed and can't be. A hashing algorithm is meant to represent data in a unique way. It is not meant to store data.