Fork me on GitHub

python常用库之base64

 

1. 什么是base64

base64是一种将不可见字符转换为可见字符的编码方式。

 

2. 如何使用

最简单的使用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import base64
 
if __name__ == '__main__':
 
    s = 'plain text'
 
    # base64编码
    t = base64.b64encode(s.encode('UTF-8'))
    print(t)
 
    # base64解码
    t = base64.b64decode(t)
    print(t)
 
    # base32编码
    t = base64.b32encode(s.encode('UTF-8'))
    print(t)
 
    # base32解码
    t = base64.b32decode(t)
    print(t)
 
    # base16编码
    t = base64.b16encode(s.encode('UTF-8'))
    print(t)
 
    # base16解码
    t = base64.b16decode(t)
    print(t)

base64.bxxencode接受一个字节数组bytes用于加密,返回一个bytes存储加密之后的内容。

base64.bxxdecode接受一个存放着密文的bytes,返回一个bytes存放着解密后的内容。

 

对URL进行编码

编码之后的+和/在请求中传输的时候可能会出问题,使用urlsafe_b64encode方法会自动将:

1
2
+映射为-
/映射为_

这样加密之后的就都是在网络上传输安全的了。

1
2
3
4
5
6
7
8
9
10
11
import base64
 
if __name__ == '__main__':
 
    s = 'hello, world'
 
    t = base64.urlsafe_b64encode(s.encode('UTF-8'))
    print(t)
 
    t = base64.urlsafe_b64decode(t)
    print(t)

使用urlsafe_b64encode相当于是base64.b64encode(s.encode('UTF-8'), b'-_'),第二个参数指定了使用哪两个字符来替换掉+和/:

1
2
3
4
5
6
7
8
9
10
11
import base64
 
if __name__ == '__main__':
 
    s = 'hello, world'
 
    t = base64.b64encode(s.encode('UTF-8'), b'-_')
    print(t)
 
    t = base64.b64decode(t, b'-_')
    print(t)

 

直接对流进行编码

加密和解密的时候可以直接传入一个流进去,base64模块加密方法会从输入流中读取数据进行加密,同时将结果写到输出流中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import base64
from io import BytesIO
 
if __name__ == '__main__':
 
    input_buff = BytesIO()
    output_buff = BytesIO()
 
    input_buff.write(b'hello, world')
    input_buff.seek(0)
 
    base64.encode(input_buff, output_buff)
    s = output_buff.getvalue()
    print(s)

 

参考资料:

1. https://docs.python.org/3.5/library/base64.html

posted @   CC11001100  阅读(7929)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示