13

Problem

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:

Code

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

Node.js v0.10.0

Outputs: ab3af8566ddd20d7efc9b314abe90755

Node.js v6.1.0

Outputs: 07625e142e4ac5961de57472657a88c1

Question

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

Update

Similar issues on GitHub:

gevorg
  • 4,273
  • 4
  • 32
  • 49

2 Answers2

26

Some inputs in Node v6+ calculate a different hash than previous Node versions.

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')
Jehy
  • 4,273
  • 1
  • 33
  • 54
robertklep
  • 174,329
  • 29
  • 336
  • 330
  • Are these encodings(binary/utf-8) differs by in-char byte order? – vp_arth May 25 '16 at 19:28
  • 1
    @vp_arth not so much byte _order_, but the way they are represented in bytes differs. I believe that `binary` is Latin-1 encoding (which is limited in the number of characters that it can represent, which I guess was the reason why the default changed to `utf-8` for Node v6). – robertklep May 25 '16 at 19:36
4

Just like mark this issue in github: https://github.com/nodejs/node/issues/6813 is about the default encoding for digests that was changed to utf8 in v5/v6 and in v4 and earlier it was binary

ccmorataya
  • 69
  • 1
  • 9