【问题标题】:How to make a checksum.dat hash file from a .txt file in Python如何在 Python 中从 .txt 文件制作 checksum.dat 哈希文件
【发布时间】:2014-12-13 22:21:56
【问题描述】:

我正在尝试创建一个名为 checksum.dat 的文件,其中包含 Python 中名为 index.txt 的文件的 SHA256 哈希。

到目前为止我的想法:

import hashlib
with open("index.txt", "rb") as file3:
    with open("checksum.dat", "wb") as file4:
        file_checksum = hashlib.sha256()
        file_checksum.update(file3)
        file_checksum.digest()

        print(file_checksum)
        file4.write(file_checksum)

我希望它将哈希打印到控制台中,并将其写入 checksum.dat 文件。

但我得到的只是这个错误:

File "...", line 97, in main
file_checksum.update(file3)
TypeError: object supporting the buffer API required

到目前为止,我在 Google 上搜索到的是,据我了解,您不能仅从字节对象或其他东西中对字符串进行哈希处理。不知道如何将我的 index.txt 变成我可以使用的对象。

有人知道如何解决这个问题吗?请记住,我是新手。

【问题讨论】:

  • 你正在使用哪个 Python 版本?

标签: python file text hash checksum


【解决方案1】:

你必须喂index.txt的内容,所以问题就出在这里:

file_checksum.update(file3)

file3 是指向index.txt 文件的文件指针,它没有文件的内容。要获取内容,请执行read()。所以以下应该解决它:

file_checksum.update(file3.read())

因此,您的完整代码将是:

import hashlib
with open("index.txt", "rb") as file3:
        file_checksum = hashlib.sha256()
        for line in file3:
            file_checksum.update(line)
            file_checksum.hexdigest()
        print(file_checksum.hexdigest())

with open("checksum.dat", "wb") as file4:        
        file4.write(bytes(file_checksum.hexdigest(), 'UTF-8'))

【讨论】:

  • 现在我得到以下异常:file4.write(file_checksum) TypeError: '_hashlib.HASH' does not support the buffer interface
  • 不要一次读取整个文件,否则您的程序会因大量输入而窒息。另外,不要使用encode(),因为它可能会改变原始表示(和哈希码)。
  • @StefanoSanfilippo - 更新了答案,现在它逐行读取并计算校验和。如果您有任何其他建议,请告诉我。
  • 几乎可以正常工作,它将 "ý?±zªíº™K[²!A‹¨Ñ†N$ŠJ…¾•«gxŽ" 放入 checksum.dat 文件中,但我们得到了正确的解决方案,即:checksum.dat 文件中的“14ca7e2ff65628dc515d43aea8029d623701a164cc6282ce1444550420b46fa3”。
猜你喜欢
  • 1970-01-01
  • 2016-07-23
  • 2022-11-24
  • 2011-11-29
  • 2012-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多