模块 - hashlib

hashlib模块


交给hash算法一串内容,hash算法会计算出一个值,该值称之为哈希值,而哈希值有三大特征:

1、只要采用hash算法一样,并且传入的内容一样,那么hash值一定一样

2、hash值的长度取决于算法,与传入内容的多少无关

3、hash值不可逆推


hash两大用途:

    1、文件内容完整性校验

    2、加密


# 传入的内容与采用的算法一样,得到的hash值一定一样

import hashlib

m = hashlib.md5()
m.update("你好".encode('utf-8'))
m.update("hello".encode('utf-8'))
m.update("哈哈".encode('utf-8'))

# "你好hello哈哈"   # hash工厂计算的是它的值
print(m.hexdigest())  # 43b2fa0da902a2d9175fb4d4b858e5d5

m1 = hashlib.md5()
m1.update("你".encode('utf-8'))
m1.update("好hello".encode('utf-8'))
m1.update("哈".encode('utf-8'))

# "你好hello哈哈"
print(m1.hexdigest())  # 43b2fa0da902a2d9175fb4d4b858e5d5




# 效验文件完整性
import hashlib
m = hashlib.md5()

with open(r'D:\python17\day16\代码.zip',mode='rb') as f:
    
    for line in f:
        m.update(line)
        
    res = m.hexdigest()
    print(res)
    
以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。

import hashlib

m = hashlib.md5()

m.update("天王".encode('utf-8'))   # 密码加盐
m.update("123egon".encode('utf-8'))
m.update("盖地虎".encode('utf-8'))

print(m.hexdigest())

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))

python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密:

import hmac

h1=hmac.new('hello'.encode('utf-8'),digestmod='md5')
h1.update('world'.encode('utf-8'))

print(h1.hexdigest())

hmac 模块注意:

#要想保证hmac最终结果一致,必须保证:

    #1:hmac.new括号内指定的初始key一样
    #2:无论update多少次,校验的内容累加到一起是一样的内容

# 操作一

import hmac
h1=hmac.new('hello'.encode('utf-8'),digestmod='md5')
h1.update('world'.encode('utf-8'))

print(h1.hexdigest()) # 0e2564b7e100f034341ea477c23f283b

# 操作二

import hmac

h2=hmac.new('hello'.encode('utf-8'),digestmod='md5')
h2.update('w'.encode('utf-8'))
h2.update('orld'.encode('utf-8'))

print(h1.hexdigest()) # 0e2564b7e100f034341ea477c23f283b

posted @ 2021-04-15 18:54  此用户名不可用  阅读(63)  评论(0)    收藏  举报