不同数组的Javascriptmd5哈希产生相同的值
使用md5npm 模块,我试图理解为什么使用两个不同的输入值运行以下命令会产生相同的散列值。
const value1 = ["test1"];
const value2 = ["test2"];
const result1 = md5(value1);
const result2 = md5(value2);
// but
const result3 = md5(JSON.stringify(value1));
const result4 = md5(JSON.stringify(value2));
// result1 === result2
// result3 !== result4
回答
查看源代码:
md5 = function (message, options) { // Convert to byte array if (message.constructor == String) if (options && options.encoding === 'binary') message = bin.stringToBytes(message); else message = utf8.stringToBytes(message); else if (isBuffer(message)) message = Array.prototype.slice.call(message, 0); else if (!Array.isArray(message) && message.constructor !== Uint8Array) message = message.toString(); // else, assume byte array already
如果您将消息的数组传递给它(在前两种情况下是这样),那么它假定您传递的是一个字节数组。
您正在向它传递一个字符串数组,因此它会中断。
- It's interesting to see code doing constructor comparisons, as that doesn't work in cross-realm situations (like a child window calling a function via `top`). (At least, that used to not work.)
- @Pointy - It still doesn't, good point. Node.js code can get away with some things browser-based code can't (I can't immediately think of how you'd get a cross-realm object reference in Node.js), but...I would've flagged it in a code review. 🙂