python 3 可以用 hashlib.sha256() 分块更新文件摘要,再用 hexdigest() 得到 64 位十六进制字符串。文件必须以二进制模式读取;与可信渠道提供的摘要一致,才能作为完整性核对的依据。sha-256 是哈希算法,不能用来解密文件,也不适合直接存储密码。

分块读取文件并计算 SHA-256
把下面代码保存为 file_hash.py。每次读取固定大小的数据并更新同一个哈希对象,文件再大也不需要一次全部读入内存。读取失败会抛出 OSError,调用者可决定如何提示。
import hashlib
from pathlib import Path
def file_sha256(path, chunk_size=8192):
if chunk_size <p>例如执行 python file_hash.py archive.zip。返回值只取决于文件字节内容;文件名、路径及修改时间不会参与这次摘要计算。</p><p><img src="https://img.php.cn/upload/image/574/561/749/1794986474444610.jpg?x-oss-process=image/resize,p_40" alt=""></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13278" title="Camoufox Open Source Anti-Detect Browser for Python Automation"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e352aa140.jpg" alt="Camoufox Open Source Anti-Detect Browser for Python Automation" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13278" title="Camoufox Open Source Anti-Detect Browser for Python Automation" class="overflowclass">Camoufox Open Source Anti-Detect Browser for Python Automation</a>
<p class="overflowclass">Camoufox 是一个基于 Firefox 构建的开源反检测浏览器,为 Python 自动化工作流程提供强大的指纹注入和反机器人检测规避功能。它与 Playwright 集成,以提供能够绕过现代机器人检测系统的隐身浏览能力。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13278" title="Camoufox Open Source Anti-Detect Browser for Python Automation" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><h2>验证分块大小不影响摘要结果</h2><p>把以下代码另存为 check_hash.py,与 file_hash.py 放在同一目录后执行。临时文件会自动清理;测试同时覆盖空文件、不同分块大小和修改一个字节的情况。</p><pre class="brush:php;toolbar:false;">import hashlib
import tempfile
from pathlib import Path
from file_hash import file_sha256
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "sample.bin"
path.write_bytes(b"abc")
expected = hashlib.sha256(b"abc").hexdigest()
assert file_sha256(path, 1) == expected
assert file_sha256(path, 8192) == expected
path.write_bytes(b"abd")
assert file_sha256(path) != expected
path.write_bytes(b"")
assert file_sha256(path) == hashlib.sha256(b"").hexdigest()
print("文件摘要断言通过")
把计算结果与可信的 SHA-256 值进行比对
校验前确认参考值来自可信的独立渠道。攻击者若能同时替换文件和参考摘要,单纯比较两者无法证明文件可信。下面用已知的 abc 摘要说明比较流程;hmac.compare_digest 可用于摘要比较,普通文件校验也可直接比较字符串。
import hashlib
import hmac
expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
actual = hashlib.sha256(b"abc").hexdigest()
assert len(expected) == 64
assert hmac.compare_digest(actual, expected)
assert not hmac.compare_digest(hashlib.sha256(b"abd").hexdigest(), expected)
print("与参考摘要一致")
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










