当使用如下代码计算md5时
crypto.createHash('md5').update('hello').digest('hex');
如果update传入的是中文字符串
crypto.createHash('md5').update('辣条').digest('hex');
计算出来的md5是
b48404099575c247af9872cd89a591fb
实际上应该是
c3ade805345a2466babaf1066ffe12bc
需要手工指定
crypto.createHash('md5').update('辣条', 'utf8').digest('hex');
原因是,update方法不传入参数的时候默认使用的是binary编码,也就是latin-1
http://npm.taobao.org/mirrors/node/latest/docs/api/buffer.html#buffer_buffer
exports.DEFAULT_ENCODING = 'buffer'; Hash.prototype.update = function(data, encoding) { encoding = encoding || exports.DEFAULT_ENCODING; if (encoding === 'buffer' && typeof data === 'string') encoding = 'binary'; this._handle.update(data, encoding); return this; };
英文编码都是兼容ASCII的,所以纯英文状态下不会出现错误,直到两个字节编码的中文,“辣”的UNICODE码是8FA3,“条”是6761,所以update会将传入的“辣条”字符串当成
new Buffer('辣条', 'binary')
来处理,于是得到的是
<Buffer a3 61>
而不是正常的
<Buffer e8 be a3 e6 9d a1>
再参与MD5运算得到的当然是错误的结果