• 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

  • 相关阅读:
    ThinkPHP5远程代码执行高危漏洞(附:升级修复解决方法)
    PowerDesigner 表格导出为excel
    ubuntu 18.04 配置远程ssh/远程ftp/远程vnc登陆
    Linux apache的运行用户和用户组
    mac系统 安装pip,用python读写excel(xlrd、xlwt)安装
    nvm 设置 nodejs 默认版本
    js基础
    Node.js 8 中的 util.promisify的详解
    HTTP协议中POST、GET、HEAD、PUT等请求方法以及一些常见错误
    MQTT简介
  • 原文地址:https://www.cnblogs.com/cc11001100/p/7789270.html
Copyright © 2020-2023  润新知