python3 字符串base64编码

在一些项目中,接口的报文是通过base64加密传输的,所以在进行接口自动化时,需要对所传的参数进行base64编码,对拿到的响应报文进行解码;

str(源字符串)--str(加密后)--str(解密)

Python 2 将 strings 处理为原生的 bytes 类型,而不是 unicode,
Python 3 所有的 strings 均是 unicode 类型。
b64encode函数的参数为byte类型,所以必须先编码


str 与 bytes 之间的类型转换如下:
str ⇒ bytes:bytes(s, encoding='utf8')
bytes ⇒ str:str(b, encoding='utf-8')
此外还可通过编码解码的形式对二者进行转换
str 编码成 bytes 格式:str.encode(s)
bytes 格式编码成 str 类型:bytes.decode(b)



import base64

s = '代码'
es = base64.b64encode(s.encode('utf-8')).decode("utf-8")
print(es) # 5Luj56CB

ds = base64.b64decode(es.encode('utf-8')).decode("utf-8")
print(ds) # 代码

参考:
https://blog.csdn.net/A18373279153/article/details/88991929
https://www.cnblogs.com/zanjiahaoge666/p/7242642.html
https://www.cnblogs.com/kanneiren/p/9981084.html

原文地址:https://www.cnblogs.com/xujinjin18/p/11556064.html