hash文件校验

import hashlib
import os
"""
mode => r  read(数字->字符个数)
mode => rb read(数字->字节个数)
字节的个数 <=> 文件的大小
"""

(1) 针对于小文件进行内容校验

def check_md5(filename):
	hs = hashlib.md5()
	with open(filename,mode="rb") as fp:			
		hs.update(fp.read())
	return hs.hexdigest()
	
res1 = check_md5("ceshi1.txt")
res2 = check_md5("ceshi2.txt")
print(res1,res2)

(2) 针对于大文件进行内容校验

# 可以通过update 把字符串分段进行加密
# 常规方法
strvar = "今天是星期五,好开心了,下周一又要考试了."
hm = hashlib.md5()
hm.update(strvar.encode())
res = hm.hexdigest()
print(res)

分段更新加密

hm = hashlib.md5()
hm.update("今天是星期五,好开心了,".encode())
hm.update("下周一又要考试了.".encode())
res = hm.hexdigest()
print(res)

# 方法一
def check_md5(filename):
	hs = hashlib.md5()
	with open(filename,mode="rb") as fp:
		while True:
			content = fp.read(10) # 一次最多读取10个字节
			if content:
				# 分批进行字符串密码更新
				hs.update(content)
			else:
				break

		return hs.hexdigest()

	
res1 = check_md5("ceshi1.txt")
res2 = check_md5("ceshi2.txt")
print(res1,res2)

# 方法二
def check_md5(filename):
	hs = hashlib.md5()
	# 计算文件大小=>返回字节数
	filesize = os.path.getsize(filename)
	with open(filename,mode="rb") as fp:
		while filesize:
			content = fp.read(10) # 一次最多读取10个字节
			hs.update(content)
			# 按照实际的字节个数读取
			filesize -= len(content)

		return hs.hexdigest()

	
res1 = check_md5("ceshi1.txt")
res2 = check_md5("ceshi2.txt")
print(res1,res2)

猜你喜欢

转载自blog.csdn.net/qq_45066628/article/details/112858783