模块(二)

hashlib/collections/shutil/logging

hashlib模块

import hashlib

# md5
h = hashlib.md5()
s = '123'
h.update(s.encode('utf-8'))
# print(h.hexdigest())                # 202cb962ac59075b964b07152d234b70

s1 = 'abc'
h.update(s1.encode('utf-8'))
# print(h.hexdigest())                 # a906449d5769fa7361d7ecc6aa3f6d28

# 加盐
s = '123'
ret = hashlib.md5('alex'.encode('utf-8'))
ret.update(s.encode('utf-8'))
# print(ret.hexdigest())                  # b75bd008d5fecb1f50cf026532e8ae67

# 动态盐
# # username = input('请输入用户名').strip()
# hs = hashlib.md5(username[::2].encode('utf-8'))
# hs.update(username.encode('utf-8'))
# print(hs.hexdigest())

# sha系列,金融类,安全类
# 随着sha系列后面的数字越高,加密越复杂,越不易破解,但是耗时越长
s4 = 'this is sha系列加密'
hsha = hashlib.sha256()
hsha.update(s4.encode('utf-8'))
# print(hsha.hexdigest())      # 979b03b7203e732700d212b0337d7525fd56cd08628cbf9202ced1847139e70f

# 文件的校验
# linux中一切皆文件,文本文件,非文本文件,音频,视频,图片...
# 无论你下载的视频,还是软件(国外的软件),往往都有一个md5值

# 练习题:对一个大文件进行校验
# 第一种
# def file_md5(path):
#     hs = hashlib.md5()
#     with open(path,'rb') as f:
#         for i in f:
#             hs.update(i)
#     return hs.hexdigest()
#
# res = file_md5(r'D:\ISO\cn_windows_10_business_edition_version_1809_updated_sept_2018_x64_dvd_84ac403f.iso')
# print(res)             # a82912d7ca091f9bf8dcd673eebf7f1c

# 第二种
def file_md5(path):
    hs = hashlib.md5()
    with open(path,'rb') as f:
        for i in f:
            hs.update(i)
    return hs.hexdigest()

res = file_md5(r'D:\ISO\cn_windows_10_business_edition_version_1809_updated_sept_2018_x64_dvd_84ac403f.iso')
print(res)             # a82912d7ca091f9bf8dcd673eebf7f1c



---------------- end --------------------

上一篇:hashlib模块


下一篇:python 字符编码