import hashlib
filename = './xx_img2_2.png'
with open(filename,"rb") as f:
file_bytes = f.read() # read file as bytes
readable_hash = hashlib.md5(file_bytes).hexdigest();
print(readable_hash)
d3526b4ecf394d12a7cf2e40ebe992d4
以下是另外一种用法,使用了 update()
函数,进行了简单封装:
def out_md5(src):
m = hashlib.md5()
m.update(src)
return m.hexdigest()
out_md5(open(filename, 'rb').read())
'd3526b4ecf394d12a7cf2e40ebe992d4'
import hashlib
filename = './xx_img2_2.png'
md5_hash = hashlib.md5()
with open(filename,"rb") as f:
# Read and update hash in chunks of 4K
for byte_block in iter(lambda: f.read(4096),b""):
md5_hash.update(byte_block)
print(md5_hash.hexdigest())
d3526b4ecf394d12a7cf2e40ebe992d4
安全增强包括添加文件锁机制防止并发修改、实现哈希值缓存功能和支持SHA-256等更安全算法。
性能优化建议使用mmap内存映射技术加速大文件读取,多线程处理文件集合,考虑使用C扩展(如pycryptodome)提升计算速度。
典型应用场景包括文件完整性校验、重复文件检测、数据一致性验证和安全审计日志。
注意:MD5已不适用于密码学安全场景,大文件处理建议添加超时机制,Windows系统需要注意文件路径编码问题。