使用hashlib的md5方法对文件进行加密,目的是为了保证文件在传输的过程中是否发生变化。

#!/usr/bin/python3
# coding:utf-8
# Auther:AlphaPanda
# Description:使用hashlib模块,对文件内容进行校验。以此来判断文件传输过程中是否发生变化,或者有损坏
# Version:1
# Date:Fri Dec 6 22:15:16 EST 2019
import hashlib
# 针对小文件的内容校验
def check_md5(file):
with open(file,mode="rb") as fp:
res = fp.read()
hs = hashlib.md5()
hs.update(res)
return hs.hexdigest() res = check_md5("ceshi1.txt")
print(res) # 针对大文件的内容校验
hs = hashlib.md5()
hs.update("你好\n世界".encode())
print(hs.hexdigest()) hs = hashlib.md5()
hs.update("你好".encode())
hs.update("\n世界".encode())
print(hs.hexdigest())
# 通过以上实验,证明一次加密文件的一行,依次加密完所有的文件内容和一次加密所有的文件内容,所获得的hash值一样。 # 大文件校验方法1:
def check2_md5(file):
hs = hashlib.md5()
with open(file,mode="rb") as fp:
while True:
content = fp.read(3)
if content:
hs.update(content)
else:
break
return hs.hexdigest() print(check2_md5("ceshi3.txt")) # 方法二:
import os
def check4_md5(file):
# 计算文件大小
file_size = os.path.getsize(file)
hs = hashlib.md5()
with open(file,mode="rb") as fp:
while file_size:
# 一次最多读取三个字节
content = fp.read(3)
hs.update(content)
file_size -= len(content)
return hs.hexdigest() print(check4_md5("ceshi4.txt"))

最新文章

  1. 手动获取spring的ApplicationContext和bean对象
  2. 【转载】浅谈HTTP中Get与Post的区别
  3. js的DOM对象
  4. eclipse + maven 搭建springMVC+Spring+mybatis 系统
  5. 封装,策略模式,Asp换脸
  6. HAML学习
  7. InteractivePNG
  8. HDU-3854 LOOPS
  9. 使用XmlReader读取xml文件之二
  10. Java中的==、equals、hasCode方法
  11. Android - DrawerLayout
  12. hotspot虚拟机的调试
  13. 【JDK1.8】JUC.Lock综述
  14. hdu-1082 Matrix Chain Multiplication---栈的运用
  15. 转:rabbitMQ 安装与管理
  16. js之制作简易红绿灯
  17. selenium与chrome浏览器及驱动的版本匹配
  18. 1060D Social Circles(贪心)
  19. 虚拟主机的IIS连接数和访问流量限制各是什么
  20. Redis入门指南之一(简介)

热门文章

  1. selenium-server--chromedriver环境
  2. 如何在java中去除中文文本的停用词
  3. oracle数据库表恢复到特定时间点
  4. Hive 教程(七)-DML基础
  5. Iterable<T>接口
  6. Redis安全策略
  7. 【原创】大叔经验分享(55)spark连接kudu报错
  8. Java APi 之 RMI远程方法调用
  9. 16 Scrapy之分布式爬虫
  10. ubuntu修改apt源