python常用库之base64

 

1. 什么是base64

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

 

2. 如何使用

最简单的使用方式

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方法会自动将:

+映射为-
/映射为_

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

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'-_'),第二个参数指定了使用哪两个字符来替换掉+和/:

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模块加密方法会从输入流中读取数据进行加密,同时将结果写到输出流中。

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

转载于:https://www.cnblogs.com/cc11001100/p/7789270.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值