Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

javascript - Why crypto.createHash returns different output in new version?

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:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...