当我更改其数据时,为什么该文件的哈希值保持不变?

Why is the hash of this file staying the same when I change its data?

我正在尝试使用这段代码对 JS 中的文件进行哈希处理:

var CryptoJS = require("crypto-js");
var fs = require('fs');

fs.readFile('./file.txt', function(err,data){
     if(err) {
         console.error("Could not open file: %s", err);
         process.exit(1);
     }
         console.log("HASH: " + CryptoJS.SHA256(data));
});

无论我在 .txt 中写入什么,生成的哈希总是:4ea5c508a6566e76240543f8feb06fd457777be39549c4016436afda65d2330e

如果我将一些字符串数据放入 CryptoJS.SHA256("text_exemple") 中,哈希将正常工作。

我在这里错过了什么?

我很好奇为什么这不起作用。首先,让我们解释一下实际发生的事情。每次调用 readFile 时都不包含文件编码类型。每 readFile docs:

If no encoding is specified, then the raw buffer is returned.

没关系。您会认为文件的缓冲区与文件中的实际数据一样可散列。然而,正在发生的事情是加密库不考虑接收缓冲区,或者更确切地说,它只考虑字符串。您可以在此处的库源代码中看到:core.js:512 它在其中执行 typeof data === 'string' 检查。

由于 typeof a_buffer === "string" 的计算结果为 false,哈希值永远不会更新。因此,您每次都会得到相同的哈希值。

所以,解决方案就是提供一个编码:

fs.readFile('./file.txt', "utf8", function(err,data){...}

或者,执行一些操作将 Buffer 转换为字符串,这样您就可以获得实际数据,例如 data.toString("utf8") 其中 data 是来自 readFile 的 Buffer .