
def cid_hash_file(path): h = hashlib.sha1() size = os.path.getsize(path) with open(path, 'rb') as stream: if size < 0xF000: h.update(stream.read()) else: h.update(stream.read(0x5000)) stream.seek(int(size/3)) h.update(stream.read(0x5000)) stream.seek(size-0x5000) h.update(stream.read(0x5000)) return h.hexdigest().upper() 上面的代码用 chatGPT 转换后是这样的
function cidHashFile(path) { const h = crypto.createHash('sha1'); const size = fs.statSync(path).size; const stream = fs.createReadStream(path); if (size < 0xF000) { stream.on('data', (chunk) => { h.update(chunk); }); } else { stream.on('data', (chunk) => { if (stream.bytesRead <= 0x5000) { h.update(chunk); } else if (stream.bytesRead >= Math.floor(size / 3) && stream.bytesRead < Math.floor(size / 3) + 0x5000) { h.update(chunk); } else if (stream.bytesRead >= size - 0x5000) { h.update(chunk); } }); } stream.on('end', () => { const result = h.digest('hex').toUpperCase(); console.log(result); }); stream.on('error', (err) => { console.error('File reading error:', err); }); } 试了不同文件计算出来的 hash 不一致,有没有大佬知道原因的?
1 dfourc 2024-12-07 17:20:09 +08:00 stream.seek 是连续的,createReadStream 流的 bytesRead 属性是无序的? |
2 kneo 2024-12-07 17:26:09 +08:00 via Android 第一个算法是取样,只读常数长度的数据。 第二个算法把所有数据都读了,首先效率应该就很差。然后文件位置的判断也不对,完全不是一个东西。 你再问一下 AI 应该就行了。 |
3 est 2024-12-07 17:32:46 +08:00 建议标题加上 chatgpt |
4 paopjian 2024-12-07 17:33:04 +08:00 不懂 python,但是如果要 debug,不如先不用 0x5000 这种特殊数字,直接全读文件再看结果. 不过你这是取了文件的 0 1/3 2/3 处位置的代码再计算 sha1? 我记得读文件的代码好像可以直接定位位置吧, 你这样是把文件全读了一遍吧, 性能不好 |
5 f360family123 OP @kneo 还真是,又问了一下就行了。已感谢 |