Python正课61 —— hashlib模块

本文内容皆为作者原创,如需转载,请注明出处:https://www.cnblogs.com/xuexianqi/p/12604326.html

一:什么是哈希hash

hash一类算法:该算法接收传入的内容,经过运算得到一串hash值

hash值的特点:

1.只要传入的内容一样,得到的hash值必然一样=====>要用明文传输密码文件完整性校验

2.不能由hash值返解成内容=======》把密码做成hash值,不应该在网络传输明文密码

3.只要使用的hash算法不变,无论校验的内容有多大,得到的hash值长度是固定的

二:hash的用途

用途1:特点2:用于密码密文传输与验证

用途2:特点1、3:用于文件完整性校验

123456asd ==> hash字符串
123456asd ==> md5 ==> hash字符串

客户端 ====> hash字符串 ====> 服务端
                           hash字符串

三:如何用hash

传的内容相同,hash值相同

import hashlib

m = hashlib.md5()
m.update('hello'.encode('UTF-8'))
m.update('world'.encode('UTF-8'))
res = m.hexdigest() # helloworld
print(res)

# fc5e038d38a57032085441e7fe7010b0

m1 = hashlib.md5()
m1.update('he'.encode('UTF-8'))
m1.update('llo'.encode('UTF-8'))
m1.update('wor'.encode('UTF-8'))
m1.update('ld'.encode('UTF-8'))
res = m1.hexdigest() # helloworld
print(res)

# fc5e038d38a57032085441e7fe7010b0

加文件内容的方式

m = hashlib.md5()

# 加内容方式1
m.update('文件所有的内容')
m.hexdigest()

# 加内容方式2(推荐)
m.update('hello'.encode('UTF-8'))
m.update('world'.encode('UTF-8'))
res = m.hexdigest() # helloworld

print(res)
m.update('文件所有的内容')
m.hexdigest()

f = open('a.txt', mode='rb')
f.seek()
f.read(2000)

模拟撞库:

import hashlib
cryptograph='aee949757a2e698417463d47acac93df'
passwds=[
    'alex3714',
    'alex1313',
    'alex94139413',
    'alex123456',
    '123456alex',
    'a123lex',
    ]
# 制作密码字典
dic = {}
for p in passwds:
    res = hashlib.md5(p.encode('UTF-8'))
    dic[p] = res.hexdigest()


# 模拟撞库得到密码
for k,v in dic.items():
    if v == cryptograph:
        print('撞库成功!明文密码是:%s' %k)
        break

老师的撞库:

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('密码是===>33[46m%s33[0m' %k)

cryptograph='aee949757a2e698417463d47acac93df'
break_code(cryptograph,make_passwd_dic(passwds))
原文地址:https://www.cnblogs.com/xuexianqi/p/12604326.html