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); }); }); } };
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.
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).
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.
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); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With