node.js hash string?

If you just want to md5 hash a simple string I found this works for me.

var crypto = require('crypto');
var name = 'braitsch';
var hash = crypto.createHash('md5').update(name).digest('hex');
console.log(hash); // 9b74c9897bac770ffc029102a200c5de

Node's crypto module API is still unstable.

As of version 4.0.0, the native Crypto module is not unstable anymore. From the official documentation:

Crypto

Stability: 2 - Stable

The API has proven satisfactory. Compatibility with the npm ecosystem is a high priority, and will not be broken unless absolutely necessary.

So, it should be considered safe to use the native implementation, without external dependencies.

For reference, the modules mentioned bellow were suggested as alternative solutions when the Crypto module was still unstable.


You could also use one of the modules sha1 or md5 which both do the job.

$ npm install sha1

and then

var sha1 = require('sha1');

var hash = sha1("my message");

console.log(hash); // 104ab42f1193c336aa2cf08a2c946d5c6fd0fcdb

or

$ npm install md5

and then

var md5 = require('md5');

var hash = md5("my message");

console.log(hash); // 8ba6c19dc1def5702ff5acbf2aeea5aa

(MD5 is insecure but often used by services like Gravatar.)

The API of these modules won't change!


Take a look at crypto.createHash(algorithm)

var filename = process.argv[2];
var crypto = require('crypto');
var fs = require('fs');

var md5sum = crypto.createHash('md5');

var s = fs.ReadStream(filename);
s.on('data', function(d) {
  md5sum.update(d);
});

s.on('end', function() {
  var d = md5sum.digest('hex');
  console.log(d + '  ' + filename);
});

Tags:

Hash

Node.Js