參考資料:
https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001399413803339f4bbda5c01fc479cbea98b1387390748000
1、Base64是一種用64個字符來表示任意二進制數據的方法。
(1)原理:將26個大寫字母、26個小寫字母、10個數字和+、-共64個字符按順序組成符號表數組,然後對待編碼字符串的二進制數據按每3個字節進行編組,每個編組再以每個數字6bit生成4個數字作爲索引號對應到符號表數組的4個字符,生成Base64編碼後的字符串。
(2)Base64編碼會把3字節的二進制數據編碼爲4字節的文本數據,長度增加33%,好處是編碼後的文本數據可以在郵件正文、網頁等直接顯示。
(3)如果要編碼的二進制數據不是3的倍數,Base64用\x00字節在末尾補足後,再在編碼的末尾加上1個或2個=號,表示補了多少字節,解碼的時候,會自動去掉。
(4)Python內置的base64可以直接進行base64的編解碼。
下面是我的學習代碼:
import base64
#用於解碼不帶=號的base64
def safe_b64decode(s):
s1 = s
while len(s1) % 4 != 0:
s1 = s1 + '='
return base64.b64decode(s1)
#測試,輸入字符串,輸出解碼或編碼結果
def Test():
while True:
s = raw_input('input a str(null to cancel):')
if s == '':
break
bDecode = False
try:
q = int(raw_input('input a func no, 1-decode, other-encode:'))
if q == 1:
bDecode = True
print '%s decoded with base64: %s' % (s, safe_b64decode(s))
continue
except BaseException, e:
if bDecode:
continue
print '%s encoded with base64:%s' % (s, base64.b64encode(s))
2、Python內置的struct模塊用於實現字符串與其他二進制數據類型的轉換。
(1)struct.pack('>I', 10240099):用於將給定的整數按前面指定格式轉換爲字符串。
(2)struct.unpack('>IH', '\xf0\xf0\xf0\xf0\x80\x80'):用於將給定的字符串按前面指定格式轉換爲數字。前面的格式符個數(>除外)決定了結果元組包含的數字個數。有關格式說明可參考官方文檔。
下面是我的學習代碼:
import struct
#不用struct的數字轉換爲字符串的方法
def IntToStr(n):
b1 = chr((n & 0xff000000) >> 24)
b2 = chr((n & 0xff0000) >> 16)
b3 = chr((n & 0xff00) >> 8)
b4 = chr(n & 0xff)
s = b1 + b2 + b3 + b4
return s
#使用struct後的轉換方法
def IntToStr1(n):
return struct.pack('>I', n)
#利用struct實現的判斷給定文件是否爲位圖的方法
def IsBmpFile(filename):
try:
with open(filename, 'rb') as f:
r = f.read(30)
t = struct.unpack('<ccIIIIIIHH', r)
if len(t) == 10 and t[0] == 'B' and t[1] == 'M':
return True
except BaseException, e:
pass
return False
#測試方法
def Test():
s = IntToStr1(10240099)
print struct.unpack('>I', s)
s = raw_input('input a filename:')
print 'Is %s a bmp file?' % s, IsBmpFile(s)
3、Python的hashlib提供了常見的摘要算法,如MD5,SHA1等等。
下面的代碼演示了利用hashlib.md5實現用戶登錄密碼的生成和比較:
import hashlib
from collections import defaultdict
#定義一個常量,表示用戶未註冊
none = 'N/A'
#初始化一個缺省值字典,用於記錄用戶註冊信息
db = defaultdict(lambda: none)
#用於生成MD5摘要
def getMD5(s):
m = hashlib.md5()
m.update(s)
return m.hexdigest()
#登錄判斷
def login(user, passwrd):
if db[user] == none:
print 'user %s not registered' % user
return False
p = db[user]
p1 = getMD5(passwrd)
if p != p1:
print 'password is invalid'
return False
print 'login success'
return True
#測試主程序
def Test():
while True:
try:
u = raw_input('input a username:')
p = raw_input('input a password:')
q = int(raw_input('input a func no, 1-create md5 password, 2-login, 0-exit'))
if q == 0:
break
if q == 1:
db[u] = getMD5(p)
if q == 2:
login(u, p)
except BaseException, e:
continue
今天就學習到這裏,下節從itertools學起。