模块之hashilb

1、hashlib模块:加密

①有解密的加密方式

②无解密的加密方式:碰撞检查 

       不同数据加密后的结果一定不一致 

       相同数据的加密结果一定是一致的

 

import hashlib

user_map = {}
def lock(msg):
    cipher = hashlib.md5(msg.encode('utf-8'))
    return cipher.hexdigest()

def regisrer():
    print('注册页面')
    user = input('user:>>>')
    pwd = input('pwd:>>>')
    lock_pwd = lock(pwd)
    user_map[user] = lock_pwd
    print(user_map)
regisrer()
# {'abc': '202cb962ac59075b964b07152d234b70'}

def login():
    print('登录页面')
    user = input('user:>>>')
    pwd = input('pwd:>>>')
    if user in user_map:
        lock_pwd = lock(pwd)
        if user_map[user] == lock_pwd:
            print('登录成功')
        else:
            print('登录失败')
    else:
        print('账号不存在')
login()

③基本使用

# part1
cipher = hashlib.md5('要被加密的字符串'.encode('utf-8'))
print(cipher.hexdigest())

cipher = hashlib.md5('abc'.encode('utf-8'))
print(cipher.hexdigest())     # 900150983cd24fb0d6963f7d28e17f72

cipher = hashlib.md5('a'.encode('utf-8'))
cipher.update('b'.encode('utf-8'))
cipher.update('c'.encode('utf-8'))
print(cipher.hexdigest())     # 900150983cd24fb0d6963f7d28e17f72


# part2
# 加盐 add salt
cipher = hashlib.md5()
msg = input('msg:>>>')
cipher.update('前盐'.encode('utf-8'))
cipher.update(msg.encode('utf-8'))
cipher.update('后烟'.encode('utf-8'))
print(cipher.hexdigest())

print(hashlib.md5('前盐123后盐'.encode('utf-8')).hexdigest())
# 597485af9593db98cc73b79738cbb3ea


# part3
cipher = hashlib.sha3_512('abc呵呵'.encode('utf-8'))
print(cipher.hexdigest())

2、hmac模块:

①加密(必须加盐)

cipher = hmac.new(''.encode('utf-8'))
cipher.update('数据'.encode('utf-8'))
print(cipher.hexdigest())    # 15b98c09b1c80b37cd8dc2b897b9b6d4

②和md5的区别:

hashlib.md5():
    可以有初始参数,可以没有初始参数
    可以通过update再添加新内容

hmac.new():
    必须有初始参数
    可以通过update再添加新内容
cipher = hmac.new(''.encode('utf-8'))
cipher.update('数据'.encode('utf-8'))
print(cipher.hexdigest())    # 15b98c09b1c80b37cd8dc2b897b9b6d4

 

posted @ 2019-04-16 17:18  TianShu  Views(159)  Comments(0Edit  收藏  举报