Python 代码转换为 Javascript 运算结果不一致

280 天前
 f360family123
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 不一致,有没有大佬知道原因的?

2108 次点击
所在节点    JavaScript
5 条回复
galikeoy
280 天前
stream.seek 是连续的,createReadStream 流的 bytesRead 属性是无序的?
kneo
280 天前
第一个算法是取样,只读常数长度的数据。
第二个算法把所有数据都读了,首先效率应该就很差。然后文件位置的判断也不对,完全不是一个东西。
你再问一下 AI 应该就行了。
est
280 天前
建议标题加上 chatgpt
paopjian
280 天前
不懂 python,但是如果要 debug,不如先不用 0x5000 这种特殊数字,直接全读文件再看结果. 不过你这是取了文件的 0 1/3 2/3 处位置的代码再计算 sha1? 我记得读文件的代码好像可以直接定位位置吧, 你这样是把文件全读了一遍吧, 性能不好
f360family123
280 天前
@kneo 还真是,又问了一下就行了。已感谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1095749

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX