python3-base64加密

在python3中base64模块中的参数是字节流,不是字符串,所以python3 base64加密字符串有两种写法

普通字符串编解码

编码

方法一:字符串切割

1
2
3
4
5
6
7
8
9
10
>>> import base64
>>> a = 'string'
>>> encrypt = base64.b64encode(a.encode('utf-8'))
>>> encrypt
b'c3RyaW5n'
>>> b = str(encrypt)
>>> b
"b'c3RyaW5n'"
>>> print(b[2:-1])
c3RyaW5n

方法二:直接转换操作

1
2
3
4
5
6
7
8
9
>>> import base64
>>> a = 'testzifuchuan'
>>> d = base64.b64encode(a.encode('utf-8'))
>>> d
b'dGVzdHppZnVjaHVhbg=='
>>> d.decode('utf-8')
'dGVzdHppZnVjaHVhbg=='
>>> str(d,'utf-8')
'dGVzdHppZnVjaHVhbg=='

解码

1
2
3
4
5
6
7
8
9
10
>>> a = 'testzifuchuan'
>>> d = base64.b64encode(a.encode('utf-8'))
>>> d
b'dGVzdHppZnVjaHVhbg=='
>>> d.decode('utf-8')
'dGVzdHppZnVjaHVhbg=='
>>> base64.b64decode(d.decode('utf-8'))
b'testzifuchuan'
>>> base64.b64decode(d.decode('utf-8')).decode('utf-8')
'testzifuchuan'

将十六进制字符串用base64编解码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> msg = "f0c6"
>>> s = bytes.fromhex(msg) #将hex的数据转换为str,并以Byte 形式存储
>>> s
b'\xf0\xc6'
>>> encoded = base64.b64encode(s) #base64编码后的形式
>>> encoded
b'8MY='
>>> str(encoded)[2:-1] #转成字符串
'8MY='
>>>
>>> decoded = base64.b64decode(encoded) #解码
>>> decoded
b'\xf0\xc6'
>>> decoded.hex() #将byte转换成16进制字符串
'f0c6'
--------------------本文结束,感谢您的阅读--------------------