day5_python之hashlib模块

用来校验文本内容
hash:一种算法 ,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
三个特点:
1.内容相同则hash运算结果相同,内容稍微改变则hash值则变
2.不可逆推
3.相同算法:无论校验多长的数据,得到的哈希值长度固定。

字符串的校验_md5
import hashlib

m = hashlib.md5()  # 使用MD5方法,拿到一个对象m
m.update('hello'.encode('utf-8'))  # md5能够校验的只能是bytes类型
m.update('world'.encode('utf-8'))
print(m.hexdigest())  # fc5e038d38a57032085441e7fe7010b0

m = hashlib.md5()
m.update('helloworld'.encode('utf-8'))  # md5能够校验的只能是bytes类型
print(m.hexdigest())  # fc5e038d38a57032085441e7fe7010b0

m = hashlib.md5('helloworld'.encode('utf-8'))
print(m.hexdigest())  # fc5e038d38a57032085441e7fe7010b0

针对文件的校验_md5
m = hashlib.md5()
with open('a.xml','rb') as f:
    for line in f:
        m.update(line)

print(m.hexdigest())#a013451de747ddb0260b068f55df4807



###下面的方法耗费内存,用上面的较好
m = hashlib.md5()
with open('a.xml','rb') as f:
    m.update(f.read())

print(m.hexdigest())#a013451de747ddb0260b068f55df4807

  

hashlib.sha3_512() #比MD5更复杂,跟MD5的使用方法是一样的, 只是调用的时候用sha3_512

 

给文件加盐
password = 'xiechao0621'
m = hashlib.md5('yihangbailushangqingtai'.encode('utf-8'))#防止撞库破解
m.update(password.encode('utf-8'))
password_md5 = m.hexdigest()    #通过MD5加密,拿到一个密文的password
print(password_md5)

  

hmac 模块
import hmac

h = hmac.new('hello'.encode('utf-8'))
h.update('world'.encode('utf-8'))
print(h.hexdigest())#0e2564b7e100f034341ea477c23f283b


h.update('hell'.encode('utf-8'))
h.update('oworld'.encode('utf-8'))
print(h.hexdigest())#57d59f3af3ec911f5afec9b5dc3829ce

h = hmac.new('hello'.encode('utf-8'))
h.update('w'.encode('utf-8'))
h.update('or'.encode('utf-8'))
h.update('ld'.encode('utf-8'))
print(h.hexdigest())#0e2564b7e100f034341ea477c23f283b  拼接的使用方法,与第一种保持一样

  

 

import hashlib
passwds=[
    'alex3714',
    'alex1313',
    'alex94139413',
    'alex123456',
    '123456alex',
    'a123lex',
    ]
def make_passwd_dic(passwds):
    dic={}
    for passwd in passwds:
        m=hashlib.md5()
        m.update(passwd.encode('utf-8'))
        dic[passwd]=m.hexdigest()
    return dic

def break_code(cryptograph,passwd_dic):
    for k,v in passwd_dic.items():
        if v == cryptograph:
            print('密码是===>\033[46m%s\033[0m' %k)

cryptograph='aee949757a2e698417463d47acac93df'
break_code(cryptograph,make_passwd_dic(passwds))

模拟撞库破解密码
模拟撞库破解密码

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


posted @ 2017-11-23 23:47  xiechao  阅读(208)  评论(0)    收藏  举报
levels of contents