Base64 是一種用 64 個字符來表示任意二進制數據的方法。
原理
- 首先,準備一個包含 64 個字符的數組:
['A', 'B', 'C', ... 'a', 'b', 'c', ... '0', '1', ... '+', '/']
- 然後,對二進制數據進行處理,每 3 個字節一組,一共是 3 x 8 = 24 bit,劃爲 4 組,每組正好 6 個 bit:
這樣我們得到4個數字作爲索引,然後查表,獲得相應的4個字符,就是編碼後的字符串。
如果要編碼的二進制數據不是 3 的倍數,最後會剩下 1 個或 2 個字節怎麼辦?Base64 用 \x00 字節在末尾補足後,再在編碼的末尾加上 1 個或 2 個 = 號,表示補了多少字節,解碼的時候,會自動去掉。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' 內建模塊—base64 '
__author__ = 'Kevin Gong'
import base64
s = base64.b64encode('在Python中使用BASE 64編碼'.encode('utf-8'))
print(s)
d = base64.b64decode(s).decode('utf-8')
print(d)
s = base64.urlsafe_b64encode('在Python中使用BASE 64編碼'.encode('utf-8'))
print(s)
d = base64.urlsafe_b64decode(s).decode('utf-8')
print(d)