hashlib模块
import hashlib # 能够把一个字符串数据类型的变量,转换成定长的密文的字符串,每一个字符都是十六进制数 # md5 结果为32位字符串,每个字符都是十六进制 # 注意:如果要对多个字符串计算md5,一定要实例化多个MD5对象 md5_obj = hashlib.md5(bytes('任意字符串作为盐',encoding='utf-8')) s = 'alex3714' md5_obj = hashlib.md5(bytes('任意字符串作为盐',encoding='utf-8')) md5_obj.update(bytes(s,encoding='utf-8')) m = md5_obj.hexdigest() print(m) # sha1 结果为40位字符串,每个字符都是十六进制.用法跟md5一样 只需要把md5改成sha1 s = 'alex3714' sha1_obj =hashlib.sha1(bytes('任意字符串作为盐',encoding='utf-8')) sha1_obj.update(bytes(s,encoding='utf-8')) s = sha1_obj.hexdigest() print(s)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 大文件md5 注意:同一个文件的时候一定要用同一个md5的实例化对象 25cd4f5e603e0da5ff5b12e445503052 def md5_file(file_name,each_size=1024): import os md5_obj = hashlib.md5() file_size = os.path.getsize(file_name) with open(file_name,'rb') as f: count = 0 while count < file_size: if count + each_size < file_size: line = f.read(each_size) count += each_size else: line = f.read(file_size-count) count = file_size md5_obj.update(line) m = md5_obj.hexdigest() return m def md5_file_compare(file1,file2,each_size=1024): file1_md5 = md5_file(file1,each_size) file2_md5 = md5_file(file2,each_size) return file1_md5,file2_md5,file1_md5==file2_md5 file1 = '测试用的文件.mp4' file2 = 'os模块.ipynb' print(md5_file_compare(file1,file2,each_size=1024))