3.7 hashlib模块

  • 加密模块, 摘要算法,散列算法,等等.它是一堆加密算法的集合.

  • hashlib如何加密?

    1. 将一个bytes类型的数据 通过hashlib进行加密返回 一个等长度的16进制数字.

    2. 过程不可逆.

    3. 相同的bytes类型的数据通过相同的加密方法得到的数字绝对相同.

    4. 不相同的bytes类型的数据通过相同的加密方法得到的数字绝对不相同.

  • 撞库: 111111, 123456, 000000,19980123,

    {'202cb962ac59075b964b07152d234b70': 123456}

  • hashlib 的用途:

    1. 密码加密.

    2. 文件一致性校验.

1.密码加密:

import hashlib
ret = hashlib.md5()
ret.update('123'.encode('utf-8'))
s = ret.hexdigest()
print(s,type(s)) 202cb962ac59075b964b07152d234b70 <class 'str'>

import hashlib
ret = hashlib.md5()
ret.update('123'.encode('utf-8'))
s = ret.hexdigest()
print(s,type(s)) 202cb962ac59075b964b07152d234b70 <class 'str'>
两个一样
import hashlib
ret = hashlib.md5()
ret.update('123fkejfkefjdefekfefka'.encode('utf-8'))
s = ret.hexdigest()
print(s,type(s)) 3ebcde7d2fc16401c8b42a7994ca34d4 <class 'str'>长度一样

2.加固定的盐

ret = hashlib.md5('xxx教育'.encode('utf-8'))
ret.update('123456'.encode('utf-8'))
s = ret.hexdigest()
print(s,type(s))

3.加动态的盐

username = input('输入用户名:').strip()
password = input('输入密码').strip()
ret = hashlib.md5(username[::2].encode('utf-8'))
ret.update(password.encode('utf-8'))
s = ret.hexdigest()
print(s)

4.sha 系列

sha系列: 安全系数高,耗时高.
加盐,加动态盐
ret = hashlib.sha512()
ret.update('123456fdklsajflsdfjsdlkafjafkl'.encode('utf-8'))
s = ret.hexdigest()
print(s,type(s))

5.文件的一致性校验

low版
import hashlib
ret = hashlib.md5()
with open('MD5文件校验',mode='rb') as f1:
   content = f1.read()
   ret.update(content)
print(ret.hexdigest())

ret = hashlib.md5()
with open('MD5文件校验1',mode='rb') as f1:
   content = f1.read()
   ret.update(content)
print(ret.hexdigest())

ret = hashlib.md5()
with open(r'D:\s23\day17\python-3.7.4rc1-embed-win32.zip',mode='rb') as f1:
   content = f1.read()
   ret.update(content)
print(ret.hexdigest())
d9c18c989c474c7629121c9d59cc429e
d9c18c989c474c7629121c9d59cc429e

分布update

分步update
s1 = '大学 最好的python'
1
ret = hashlib.md5()
ret.update(s1.encode('utf-8'))
print(ret.hexdigest())
2
ret = hashlib.md5()
ret.update('大学'.encode('utf-8'))
ret.update(' 最好的python'.encode('utf-8'))
print(ret.hexdigest()) # 90c56d265a363292ec70c7074798c913
hegit版
import hashlib
def md5_file(path):
   ret = hashlib.md5()
   with open(path,mode='rb') as f1:
       while 1:
           content = f1.read(1024)
           if content:
               ret.update(content)
           else:
               return ret.hexdigest()


print(md5_file(r'D:\s23\day17\python-3.7.4rc1-embed-win32.zip'))
posted @ 2019-07-12 20:07  God_with_us  阅读(164)  评论(0编辑  收藏  举报