前言 在之前的文章,分享过hashlib,这次看下另外一个加密 模块--base64
base64 加密模块常用的方法有:
函数 | 参数 | 描述 | 使用 | 返回值 |
---|---|---|---|---|
encodestring | Byte | 进行base64加密 | base64.encodestring('hi') | Byte |
decodestring | Byte | 对base64解密 | base64.decodestring(b'aGVsbG8=\n') | Byte |
encodebytes | Byte | 进行base64加密 | base64.encodebytes(b'hi') | Byte |
decodebytes | Byte | 进行base64解密 | base64.decodebytes(b'aGVsbG8=\n') | Byte |
那么我们用代码演示下:
import base64
print("加密hello")
encode_base64 = base64.encodestring(b'hello')
print(encode_base64.decode("utf-8"))
print("解密")
decode_base64 = base64.decodestring(b'aGVsbG8=')
print(decode_base64.decode("utf-8"))
import base64
print("加密hello")
encode_base64 = base64.encodebytes(b'hello')
print(encode_base64.decode("utf-8"))
print("解密")
decode_base64 = base64.decodebytes(b'aGVsbG8=')
print(decode_base64.decode("utf-8"))
结果:
加密hello
aGVsbG8=
解密
hello
加密hello
aGVsbG8=
解密
hello
这样,我们实际中,也可以用到base64加密,例如一个注册登录的程序,演示加密和解密的用法
import base64
import pickle
def write(user):
# 使用 dumps() 函数将 tup1 转成 p1
with open("a.txt", 'wb') as f: # 打开文件
pickle.dump(user, f) # 用 dump 函数将 Python 对象转成二进制对象文件
def read():
with open("a.txt", 'rb') as f: # 打开文件
t3 = pickle.load(f) # 将二进制文件对象转换成 Python 对象
return t3
def login(username,password)->bool:
userquery=read()
if username not in userquery.keys():
return False
passwordbase=base64.encodestring(bytes(password,encoding='utf-8')).decode('utf-8')
print(passwordbase)
if passwordbase ==userquery[username]:
return True
return False
def register(username:str,password:str)-> bool:
if username is None or password is None:
return False
passwordhast=base64.encodestring(bytes(password,encoding='utf-8'))
user={username:passwordhast.decode("utf-8")}
print(user)
write(user)
return True
if __name__=="__main__":
register("lieizi",'hello')
print(login('lieizi','hello'))
结果:
{'lieizi': 'aGVsbG8=\n'}
aGVsbG8=
True
这样就实现了基于base64加密 和pickle的数据存储,在实际的项目中使用到加密的时候,可以用到这个方式,当然,hashlib也可以,大家经常用,看习惯用什么吧,在实际的项目中,大家都会存储到数据库,这里演示的事基于pickle得存储。
这个例子不仅演示了base64,顺便把之前学习的pickle页练习了一遍,在我们日常的学习中也是这样的,我们要善于去学完,结合实际的去运用,学着后面的,但是前面的也要进行巩固。
后记
发现问题,解决问题。遇到问题,慢慢解决问题即可。