作者:风云变幻1892_602 | 来源:互联网 | 2023-10-11 12:55
hashlib1.常见的几种加密方法及其使用方法:importhashlib#md5hashhashlib.md5()hash.update(bytes(admin,encoding
hashlib
1.常见的几种加密方法及其使用方法:
import hashlib
# md5
hash = hashlib.md5()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
print(hash.digest())
'''
21232f297a57a5a743894a0e4a801fc3
b'!#/)zW\xa5\xa7C\x89J\x0eJ\x80\x1f\xc3'
'''
# sha1
hash = hashlib.sha1()
hash.update(bytes('1', encoding='utf-8'))
print(hash.hexdigest())
'''
356a192b7913b04c54574d18c28d46e6395428ab
'''
# sha256
hash = hashlib.sha256()
hash.update(bytes('1', encoding='utf-8'))
print(hash.hexdigest())
'''
6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b
'''
# sha384
hash = hashlib.sha384()
hash.update(bytes('1', encoding='utf-8'))
print(hash.hexdigest())
'''
47f05d367b0c32e438fb63e6cf4a5f35c2aa2f90dc7543f8a41a0f95ce8a40a313ab5cf36134a2068c4c969cb50db776
'''
# 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('自己定义的口味', encoding='utf-8'))
hash.update(bytes('1', encoding='utf-8'))
print(hash.hexdigest())
'''
0bdd27adb563c7c3198b00de20a9a972
'''
注意事项:加密算法无法直接对一个字符或者字符串加密,我们必须这些字符串转换成bytes类型再进行加密
课后拓展:将之前的用户登录程序,拓展成一个可以安全的,给用户密码加密的程序
import hashlib
def md5(arg):
ooo = hashlib.md5(bytes("吴文", encoding='utf-8'))
ooo.update(bytes(arg, encoding='utf-8'))
return ooo.hexdigest()
def register(user, pwd):
with open('db', 'a', encoding='utf-8') as f:
pwd = md5(pwd)
temp = user + '|' + pwd + '\n'
f.write(temp)
def login(user, pwd):
with open('db', 'r', encoding='utf-8') as f:
for line in f:
user1, pwd1 = line.strip().split('|')
if user == user1 and md5(pwd) == pwd1:
return True
def main():
i = input("1,登录;2,注册 :")
if i == '2':
user = input("用户名:")
pwd = input("密码:")
register(user, pwd)
elif i == 1:
user = input("用户名:")
pwd = input("密码:")
if login(user, pwd):
print("登陆成功")
else:
print("登陆失败")
main()