Base64编码和解码

Base64 不是加密算法,只是一种编码方式,数据从一种形式转换为另一种形式进行传输/存储。Base64 就是一种基于64个可打印字符来表示二进制数据的方法。
Base64要求把每三个8Bit的字节转换为四个6Bit的字节(38 = 46 = 24),然后把6Bit再添两位高位0,组成四个8Bit的字节,也就是说,转换后的字符串理论上将要比原来的长1/3。最后,用一个码表来得到我们想要的字符串,这就是 Base64编码。
码表:

索引
对应字符
索引
对应字符
索引
对应字符
索引
对应字符
0
A
17
R
34
i
51
z
1
B
18
S
35
j
52
0
2
C
19
T
36
k
53
1
3
D
20
U
37
l
54
2
4
E
21
V
38
m
55
3
5
F
22
W
39
n
56
4
6
G
23
X
40
o
57
5
7
H
24
Y
41
p
58
6
8
I
25
Z
42
q
59
7
9
J
26
a
43
r
60
8
10
K
27
b
44
s
61
9
11
L
28
c
45
t
62
+
12
M
29
d
46
u
63
/
13
N
30
e
47
v


14
O
31
f
48
w


15
P
32
g
49
x


16
Q
33
h
50
y


Python 中集成了base64 模块,可用于对二进制数据进行编码解码操作:

>>> a = "Hello world"
>>> b = base64.encode(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: encode() missing 1 required positional argument: 'output'
>>> 
>>> 
>>> b = base64.b64encode(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.8/base64.py", line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
>>> 
>>> 
>>> 
>>> a = b"Hello world"
>>> b = base64.b64encode(a)
>>> b
b'SGVsbG8gd29ybGQ='
>>> c = base64.b64decode(b)
>>> c
b'Hello world'
>>> d = b.decode('ascii')
>>> d
'SGVsbG8gd29ybGQ='
>>> e = base64.b64decode(d)
>>> e
b'Hello world'
>>>

可以看到使用 base64.b64encode 进行编码时,只能时二进制数据,如果输入时 str 文本,将报错 TypeError。
而使用 base64.b64decode 解码时,字符串和字节床都可以作为输入。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐