参考资料:
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学起。