node.js hash string?

314,926

Solution 1

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);
});

Solution 2

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

Solution 3

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!

Solution 4

sha256("string or binary");

I experienced issue with other answer. I advice you to set encoding argument to binary to use the byte string and prevent different hash between Javascript (NodeJS) and other langage/service like Python, PHP, Github...

If you don't use this code, you can get a different hash between NodeJS and Python...

How to get the same hash that Python, PHP, Perl, Github (and prevent an issue) :

NodeJS is hashing the UTF-8 representation of the string. Other languages (like Python, PHP or PERL...) are hashing the byte string.

We can add binary argument to use the byte string.

Code :

const crypto = require("crypto");

function sha256(data) {
    return crypto.createHash("sha256").update(data, "binary").digest("base64");
    //                                               ------  binary: hash the byte string
}

sha256("string or binary");

Documentation:

  • crypto.createHash(algorithm[, options]): The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform.
  • hash.digest([encoding]): The encoding can be 'hex', 'latin1' or 'base64'. (base 64 is less longer).

You can get the issue with : sha256("\xac"), "\xd1", "\xb9", "\xe2", "\xbb", "\x93", etc...

  • Other languages (like PHP, Python, Perl...) and my solution with .update(data, "binary") :

      sha1("\xac") //39527c59247a39d18ad48b9947ea738396a3bc47
    
  • Nodejs by default (without binary) :

      sha1("\xac") //f50eb35d94f1d75480496e54f4b4a472a9148752
    

Solution 5

Simple One Liners:

If you want UTF8 text hash:

const hash = require('crypto').createHash('sha256').update('Hash me', 'utf8').digest('hex');

If you want to get the same hash with Python, PHP, Perl, Github:

const hash = require('crypto').createHash('sha256').update('Hash me', 'binary').digest('hex');

You can also replace 'sha256' with 'sha1', 'md5', 'sha256', 'sha512'

Share:
314,926
Harry
Author by

Harry

Updated on July 08, 2022

Comments

  • Harry
    Harry almost 2 years

    I have a string that I want to hash. What's the easiest way to generate the hash in node.js?

    The hash is for versioning, not security.

  • balupton
    balupton almost 12 years
    Woot woot, if you do require('crypto').createHash('md5').update(STRING_TO_BE_HASH‌​ED).digest("hex") you got a one-liner. Cheers mate!
  • Valjas
    Valjas about 11 years
    I think it's much easier and efficient to utilize Crypto rather than bringing in a whole new module.
  • pvorb
    pvorb about 11 years
    From the current Node.js docs: "Stability: 2 - Unstable; API changes are being discussed for future versions. Breaking changes will be minimized." The API of my module won't change. When I initially wrote the module, there was no crypto module built into the platform. Another advantage is that you can use my module on the server as well as the client side. But it is totally up to you, what library you use.
  • Max
    Max about 11 years
    Was getting some issues using .update multiple times (github.com/joyent/node/issues/749) when trying to use timbooo's solution, using the one-liner fixed it (because the hash object is recreated every time).
  • GJK
    GJK almost 11 years
    The build in Crypto hashes kept giving me the 'hash update failed' BS. Finally I moved to the MD5 module and it worked just fine. Also easier to call (slightly). Thank you.
  • Geek Stocks
    Geek Stocks over 10 years
    +1 for an option that stays away from the (2) - Unstable nature of the Crypto API!
  • Bartvds
    Bartvds over 10 years
    I've fixed a weird sha1 problem on node 0.11.x on my Windows machine by swapping the standard crypto use for this module.
  • Robert Levy
    Robert Levy about 10 years
    it's marked as stable now, should probably delete this answer
  • pvorb
    pvorb about 10 years
    @RobertLevy Where's that info from? The official docs still say it's unstable
  • Jake Cobb
    Jake Cobb almost 10 years
    In the v0.6.18 docs linked in @timbooo's answer, it's marked as Stable (3). The current (v0.10.29) docs show Unstable (2).
  • pvorb
    pvorb almost 10 years
    @JakeCobb Yes. I added that reason after writing the initial answer.
  • Con Antonakos
    Con Antonakos about 9 years
    The require('MD5') module declares it being insecure. Can we still have confidence in using it?
  • pvorb
    pvorb about 9 years
    Do you mean the statement "Warning: MD5 is an insecure hashing algorithm. Don't use it unless you know what you are doing!" in the project README? This is about MD5 being an insecure hashing algorithm (see the security section of the Wikipedia article for MD5). The library is compliant to the standard though and very stable.
  • pvorb
    pvorb about 9 years
    I removed that statement since it is misleading about the quality of the software.
  • DucRP
    DucRP almost 9 years
    What is the s.on() function doing? Is it registering the md5sum.update(d) function to execute every time there is data being read from the ReadStream?
  • Mikel
    Mikel almost 9 years
    Any way to change the length of the string? Not only 32 characters, 64 or 128 or a different number.
  • Frank Nocke
    Frank Nocke over 8 years
    @YoniDor Did you try fs.readsync? — Digesting in a classic while-loop, then be sure that it's done... ➝ stackoverflow.com/a/21219407/444255
  • Ties
    Ties almost 8 years
    @Mikel try if there are other hash algorithms that suit your needs, md5 is always 32 characters.
  • vitor_gaudencio_oliveira
    vitor_gaudencio_oliveira almost 8 years
    "MD5" is deprecated, you have to use "md5" (lowercase) instead. Example: $ npm install md5
  • pvorb
    pvorb almost 8 years
    @vitor_gaudencio_oliveira Thanks for the note. I updated the answer.
  • balupton
    balupton over 7 years
    What do the RSA- prefixes do?
  • blimpse
    blimpse over 6 years
    OP wants to hash a string, not a file.
  • Michael
    Michael over 5 years
    If I have lots of strings to hash, it is less efficient to keep calling crypto.createHash instead of somehow re-using the result?
  • Gabriel Augusto
    Gabriel Augusto almost 3 years
    Hi ! How can I make the opposite? Given a certain hash and a certain string, check if the string is equal the hash
  • RedGuy11
    RedGuy11 almost 3 years
    isnt md5 deprecated and insecure?
  • Maf
    Maf almost 3 years
    Thanks for editing @marc_s. Feel free to do so.
  • KyleFarris
    KyleFarris over 2 years
    @RedGuy11 It's not deprecated at all. It IS very insecure for hashing passwords but there are many other use cases for hashing other than passwords. For example, creating MD5 checksums for files.
  • Curcuma_
    Curcuma_ over 2 years
    @balupton one liners come with a huge cost
  • Bruno Peixoto
    Bruno Peixoto about 2 years
    How do I convert back the hash to the string? :(