gevorg gevorg - 6 months ago 27
Node.js Question

Node.js crypto.createHash changed output in new version

I have node.js module that is using

crypto.createHash
to generate
md5
hash.

Recently I noticed that hash generated by
crypto
module is different in new versions:

My code

require('crypto').createHash('md5').update('¥').digest('hex')


For node.js v0.10.0

Outputs:
ab3af8566ddd20d7efc9b314abe90755


For node.js v6.1.0

Outputs:
07625e142e4ac5961de57472657a88c1


I was wondering what causes that in new version and how can I solve this?

UPDATE

Similar issues on GitHub:


Answer

In your particular example, I don't see any differences at all in the console output (they show up as b%/YÓHNc in my terminal), but outputting bytes without any encoding to a terminal may cause all kinds of issues (perhaps Node 6 sets the terminal in some way that it will show "more"). It's better to output using hex if you want to log it.

However, I'm guessing that you may be running into another problem, where for some inputs Node v6 calculates a different hash than previous Node versions. That's something that I happened to run into last week, using an external library that calculated MD5 hashes (issue here).

Basically, when you pass a string to .update(), with Node versions before v6 the default encoding was binary, but for Node v6 that changed to utf-8.

For example, take this code:

require('crypto').createHash('md5').update('¥').digest('hex')

This outputs ab3af8566ddd20d7efc9b314abe90755 on Node pre-6 and 07625e142e4ac5961de57472657a88c1 on Node 6.

If you want Node 6 to output the same as pre-6 versions, you have to tell .update() to use binary encoding:

require('crypto').createHash('md5').update('¥', 'binary').digest('hex')

Or the other way around (make Node pre-6 output the same as 6):

require('crypto').createHash('md5').update('¥', 'utf-8').digest('hex')
Comments