廖雪峰python3复习总结——day10-3

Base64:一种用64个字符来表示任意二进制数据的方法。Base64编码会把3字节的二进制数据编码为4字节的文本数据,长度增加33%,好处是编码后的文本数据可以在邮件正文、网页等直接显示。如果要编码的二进制数据不是3的倍数,最后会剩下1个或2个字节怎么办?Base64用\x00字节在末尾补足后,再在编码的末尾加上1个或2个=号,表示补了多少字节,解码的时候,会自动去掉。

import base64
def safe_base64_decode(s):
    if len(s)%4==0:
        print(s)
        return base64.b64decode(s)
    else:
        str = s.decode('utf-8', errors='strict')
        for i in range(len(s)%4):
            str=str+"="
        s=str.encode("utf-8",errors="strict")
        print(s)
        return base64.b64decode(s)

struct:structpack函数把任意数据类型变成bytes,unpackbytes变成相应的数据类型。

练习:

def bmp_info(data):
    data1=struct.unpack('<ccIIIIIIHH',data[0:30])
    if data1[0]==b'B' and data1[1]==b'M':
        print('这个文件是位图')
        return {
            'width': data1[6],
            'height': data1[7],
            'color': data1[9]
        }
    else:
        return None

hashilib:Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等。摘要算法又称哈希算法、散列算法。它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用16进制的字符串表示)。

def login(user, password):
    md5 = hashlib.md5()
    md5.update(password.encode('utf-8'))
    return db[user]==md5.hexdigest()
def login(username, password):
    user = db[username]
    return user.password == get_md5(password+user.salt)

Hmac算法:Keyed-Hashing for Message Authentication。它通过一个标准算法,在计算哈希的过程中,把key混入计算过程中。 Hmac算法针对所有哈希算法都通用,无论是MD5还是SHA-1。采用Hmac替代我们自己的salt算法,可以使程序算法更标准化,也更安全。hmac输出的长度和原始哈希算法的长度一致。需要注意传入的key和message都是bytes类型,str类型需要首先编码为bytes

def hmac_md5(key, s):
    return hmac.new(key.encode('utf-8'), s.encode('utf-8'), 'MD5').hexdigest()

class User(object):
    def __init__(self, username, password):
        self.username = username
        self.key = ''.join([chr(random.randint(48, 122)) for i in range(20)])
        self.password = hmac_md5(self.key, password)
def login(username, password):
    user = db[username]
    return user.password == hmac_md5(user.key, password)

猜你喜欢

转载自blog.csdn.net/weixin_41124748/article/details/82825375