python b64encode_Python base64模块详解 | 学步园
Python base64模塊是用來作base64編碼解碼的。
最簡單的加解密實例:
import base64
str1 = 'djhui'
str2 = base64.b64encode(str1)
str3 = base64.b64decode(str2)
Python base64模塊真正用的上的方法只有8個,分別是encode, decode, encodestring, decodestring, b64encode,b64decode, urlsafe_b64decode,urlsafe_b64encode。他們8個可以兩兩分為4組,encode,decode一組,專門用來編碼和解碼文件的,也可以對StringIO里的數據做編解碼;encodestring,decodestring一組,專門用來編碼和解碼字符串; b64encode和b64decode一組,用來編碼和解碼字符串,并且有一個替換符號字符的功能。這個功能是這樣的:因為base64編碼后的字符除
了英文字母和數字外還有三個字符 + / =, 其中=只是為了補全編碼后的字符數為4的整數,而+和/在一些情況下需要被替換的,b64encode和b64decode正是提供了這樣的功能。至于什么情況下+和/需要被替換,最常見的就是對url進行base64編碼的時候。urlsafe_b64encode和urlsafe_b64decode 一組,這個就是用來專門對url進行base64編解碼的,實際上也是調用的前一組函數。
Python base64模塊加/解密例子:#-*- encoding:gb2312 -*-
import base64
import StringIO
a = "this is a test"
b = base64.encodestring(a) # 對字符串編碼
print b
print base64.decodestring(b) # 對字符串解碼
c = StringIO.StringIO()
c.write(a)
d = StringIO.StringIO()
e = StringIO.StringIO()
c.seek(0)
base64.encode(c, d) # 對StringIO內的數據進行編碼
print d.getvalue()
d.seek(0)
base64.decode(d, e) # 對StringIO內的數據進行解碼
print e.getvalue()
a = "this is a +test"
b = base64.urlsafe_b64encode(a) # 進行url的字符串編碼
print b
print base64.urlsafe_b64decode(b)
上面的encode函數和decode函數的參數也可以是文件對象:f1 = open('aaa.txt', 'r')
f2 = open('bbb.txt', 'w')
base64.encode(f1, f2)
f1.close()
f2.close()
總結
以上是生活随笔為你收集整理的python b64encode_Python base64模块详解 | 学步园的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中进制chr_python中
- 下一篇: python中2d_【IT专家】如何在P