zoukankan      html  css  js  c++  java
  • Python中的base64模块

      本文介绍Python 2.7中的base64模块,该模块提供了基于rfc3548的Base16, 32, 64编解码的接口。官方文档,参考这里

      该模块提供两套接口,传统接口基于rfc1521的Base64,当前接口基于rfc3548的Base16/32/64编码规范,本文只介绍当前的接口。

      当前接口在Python 2.4中就被引进,关于Base64编码格式提供了以下六种接口,便于高效灵活地实现需要的编解码工作。

    1. b64encode(s, altchars=None)
    2. b64decode(s, altchars=None)
    3. standard_b64encode(s)
    4. standard_b64decode(s)
    5. urlsafe_b64encode(s)
    6. urlsafe_b64decode(s)

      其中以"*encode"结尾的方法用于将二进制串转为base64编码格式的字符串,以“*decode”结尾的方法用于将base64格式的字符串重新转为二进制串。

      我们详细查看前两个方法,注意到b64encode()和b64decode()接收同样形式的参数。其中 s 是要编/解码的字符串;默认参数altchars的可选值必须是长度至少两字节的字符串(第二个字符后的内容将被忽略),该方法表示在编/解码过程中将使用参数altchars中的前两个字符替换标准Base64字符集中的'+'和'/'。

      因此方法3和4中的base64.standard_b64encode(s)和base64.standard_b64decode(s)等价于base64.b64encode(s)和base64.b64decode(s)。而方法5和6中的base64.urlsafe_b64encode(s)和base64.urlsafe_b64decode(s)分别等价于base64.b64encode(s , '-_')和base64.b64decode(s , '-_'),即在编/解码过程中使用'-'和'_'替代标准Base64字符集中的'+'和'/',生成可以在URL中使用的Base64格式文本。

      使用示例:

     1 >>> import base64
     2 >>> print base64.b64encode('Hello, I am Darren!') 
     3 SGVsbG8sIEkgYW0gRGFycmVuIQ==
     4 >>>
     5 >>> print base64.b64decode('SGVsbG8sIEkgYW0gRGFycmVuIQ==')
     6 Hello, I am Darren!
     7 >>>
     8 >>> print base64.b64encode('ixb7x1dxfbxefxff')
     9 abcd++// 
    10 >>> 
    11 >>> print base64.b64encode('ixb7x1dxfbxefxff', '-_') 
    12 abcd--__ 
    13 >>> 
    14 >>> print base64.urlsafe_b64encode('ixb7x1dxfbxefxff') 
    15 abcd--__ 
    16 >>>
    17 >>> base64.urlsafe_b64decode('adcd--__') 
    18 'ixb7x1dxfbxefxff'

      本模块还提供了Base32和Base16编解码接口:  

    1. b32encode(s)    
    2. b32decode(s, casefold=False, map01=None)  

      Base16编解码:

    1. b16encode(s)
    2. b16decode(s, casefold=False)

      其中参数s都是要编/解码的字符串,关于Base16/32编码规范,请参考rfc4648rfc3548,本文只关注Base64。

  • 相关阅读:
    ERROR: epmd error for host "yourhostname": timeout
    leetcode485
    leetcode463
    leetcode496
    leetcode344
    leetcode412
    leetcode500
    leetcode476
    leetcode557
    leetcode461
  • 原文地址:https://www.cnblogs.com/Security-Darren/p/3853054.html
Copyright © 2011-2022 走看看