小文件
import hashlib
import base64
filePath = "test.txt"
with open(filePath, "rb") as f:
fileData = f.read()
sha1 = hashlib.sha1()
sha1.update(fileData)
fileHash = base64.b64encode(sha1.digest()).decode('utf-8 ')
print(fileHash)
print(base64.b64decode(fileHash).hex())
在linux中,可以使用指令sha1sum test.txt
验证
大文件
import hashlib
import base64
filePath = "test.txt"
sha1 = hashlib.sha1()
with open(filePath, "rb") as f:
while True:
fileData = f.read(2048)
if not fileData:
break
sha1.update(fileData)
fileHash = base64.b64encode(sha1.digest()).decode('utf-8 ')
print(fileHash)
print(base64.b64decode(fileHash).hex())