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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM