hashlib模块

hashlib

1.常见的几种加密方法及其使用方法:

#1、 md5
hash = hashlib.md5()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
print(hash.digest())
#21232f297a57a5a743894a0e4a801fc3
#b'!#/)zWxa5xa7Cx89Jx0eJx80x1fxc3'
#2、sha1
hash = hashlib.sha1()
hash.update(bytes('1', encoding='utf-8'))
print(hash.hexdigest())
#356a192b7913b04c54574d18c28d46e6395428ab
#3、sha256
hash = hashlib.sha256()
hash.update(bytes('1', encoding='utf-8'))
print(hash.hexdigest())
#6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b
#4、sha384
hash = hashlib.sha384()
hash.update(bytes('1', encoding='utf-8'))
print(hash.hexdigest())
#47f05d367b0c32e438fb63e6cf4a5f35c2aa2f90dc7543f8a41a0f95ce8a40a313ab5cf36134a2068c4c969cb50db776
#5、sha512
hash = hashlib.sha512()
hash.update(bytes('1', encoding='utf-8'))
print(hash.hexdigest())
#4dff4ea340f0a823f15d3f4f01ab62eae0e5da579ccb851f8db9dfe84c58b2b37b89903a740e1ee172da793a6e79d560e5f7f9bd058a12a280433ed6fa46510a

缺陷:因为每台电脑都可以进行加密,有些机器会一直运算产生密文映射库

    所以以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。

    因此,有必要对加密算法中添加自定义key再来做加密。

import hashlib
 
# md5
hash = hashlib.md5()
hash = hashlib.md5(bytes('可以进行2重加密', encoding='utf-8'))
hash.update(bytes('1', encoding='utf-8'))
print(hash.hexdigest())

注意事项:加密算法无法直接对一个字符或者字符串加密,我们必须这些字符串转换成bytes类型再进行加密

#加密登录注册系统
import hashlib
def md5(arg): #ooo = hashlib.md5() ooo = hashlib.md5(bytes("acker",encoding = "utf-8")) #md5里面还可以加参数,进行第2次加密 ooo.update(bytes('arg', encoding='utf-8')) return ooo.hexdigest() def login(user,pwd): with open("db","r",encoding="utf-8") as f: for line in f : u,p = line.strip().split("|") if u == user and p == md5(pwd): return True def register(use,pwd): with open("db","a",encoding="utf-8") as f: temp = user + "|" + md5(pwd) f.write(temp) i = input("1,登录;2,注册") if i == "2": user = input("用户名:") pwd = input("密码:") register(user,pwd) elif i == "1": user = input("用户名:") pwd = input("密码:") r = login(user,pwd) if r : print("登录成功") else: print("登录失败")
原文地址:https://www.cnblogs.com/Acekr/p/7426244.html