我从node.js中的Internet源获取一个大的,经过gzip压缩的JSON文件。该源还提供包含SHA256哈希的元文件。如果我将文件写入磁盘并对生成的文件求和,则哈希匹配;但是,当在NodeJS中对缓冲区求和时,散列不匹配。
const https = require('request-promise-native');
const request = require('request');
const zlib = require('zlib');
const crypto = require('crypto');
const getList = async (list) => {
// Start by getting meta file to SHA result
const meta = await https(`https://example.com/${list}.meta`);
const metaHash = meta.match(/sha256:(.+)$/im)[1].toLowerCase();
// metaHash = "f36c4c75f1293b3d3415145d78a1ffc1b8b063b083f9854e471a3888f77353e1"
// Download and unzip whole file
const chunks = [];
const file = await new Promise((resolve, reject) => {
const stream = request(`https://example.com/${list}.json.gz`);
stream.on('data', chunk => chunks.push(chunk));
stream.on('error', reject);
stream.on('end', () => {
const buffer = Buffer.concat(chunks);
// Unzip
zlib.gunzip(buffer, (error, unBuffer) => {
// TEST: Write to disk
fs.writeFile('/tmp/test.json', unBuffer);
// Check SHA hash
const afterHash = crypto.createHash('sha256');
afterHash.update(unBuffer);
const hash = afterHash.digest('hex');
// hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
// metaHash =/= hash
if (metaHash === hash) resolve(unBuffer.toString());
else {
// reject(`SHA hashes do not match for ${list}`);
console.log(`${list}\n${metaHash}\n${hash}`);
}
});
});
});
};
但是从我的macOS终端,它匹配:
$ sha256sum /tmp/test.json
f36c4c75f1293b3d3415145d78a1ffc1b8b063b083f9854e471a3888f77353e1 /tmp/test.json
这让我相信文件已经下载并正确解压缩。我是否错误地实现了node.js加密?我做错了什么吗?谢谢!
更新
我刚刚意识到我从e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
获取了与我尝试的每个文件相同的哈希crypto
,所以我在这里肯定做错了...
答案 0 :(得分:0)
您的e3b0c...
是空序列的SHA-256,即零输入字节。
答案 1 :(得分:0)
我从未弄清楚我做错了什么。我用hasha代替了,解决了这个问题。
const hasha = require('hasha');
...
// Unzip
zlib.gunzip(buffer, (error, unBuffer) => {
// Check SHA hash
const hash = hasha(unBuffer, { algorithm: 'sha256' });
if (metaHash === hash) resolve(unBuffer.toString());
else reject(`SHA hashes do not match for ${list}`);
});