Appearance
python中的加解密主要有hashlib和base64两种,hashlib安全系数更高但它是单向加密,也就是无法解密;而base64支持解密操作。
hashlib常用加密方法 
| 函数名 | 参数 | 介绍 | 举例 | 返回值 | 
|---|---|---|---|---|
| md5 | byte | Md5算法加密 | hashlib.md5(b'hello') | Hash对象 | 
| sha1 | byte | Sha1算法加密 | hashlib.sha1(b'hello') | Hash对象 | 
| sha256 | byte | Sha256算法加密 | hashlib.sha256(b'hello') | Hash对象 | 
| sha512 | byte | Sha512算法加密 | hashlib.sha512(b'hello') | Hash对象 | 
案例:客户端生成token,服务器端需要校验token是否被篡改过。
python
import hashlib
import time
base_sign = 'cvking'  # 基础凭证
# 客户端生成token
def custom():
    a_timestamp = int(time.time())  # 时间戳
    _token = f'{base_sign}{a_timestamp}'  # 生成加密前的token
    hashobj = hashlib.sha1(_token.encode('UTF-8'))  # 加密
    token = hashobj.hexdigest()
    return token, a_timestamp
# 校验token是否正确
def b_service_check(token, timestamp1):
    _token = f'{base_sign}{timestamp1}'
    b_token = hashlib.sha1(_token.encode('utf-8')).hexdigest()
    return token == b_token
if __name__ == '__main__':
    need_help_token, timestamp = custom()  # 返回了两个参数,可以使用两个参数接收
    result = b_service_check(need_help_token, timestamp)  # 校验token是否被篡改过
    if result:
        print('a合法')
    else:
        print('a不合法')base64常用方法 
上面俩个和下面两个功能是一样的,官方更推荐下面两种的写法。
| 函数名 | 参数 | 介绍 | 举例 | 返回值 | 
|---|---|---|---|---|
| encodestring | byte | 加密 | base64.encodestring(b'py') | byte | 
| decodestring | byte | 解密 | base64.decodestring(b'b'cHk=\n'') | byte | 
| encodebytes | byte | 加密 | base64.encodebytes(b'py') | byte | 
| decodebytes | byte | 解密 | base64.decodebytes(b'b'cHk=\n'') | byte | 
python
import base64
replace_one = '%'
replace_two = '$'
# 加密,传递字符串或bytes类型
def encode(data):
    if isinstance(data, str):
        data = data.encode('utf-8')
    elif isinstance(data, bytes):
        data = data
    else:
        raise TypeError('您传递了一个错误的数据类型')
    _data = base64.encodebytes(data).decode('utf-8')
    return _data.replace('z', replace_one).replace('2', replace_two)  # 对加密后的字符串进行替换
# 解密
def decode(data):
    if not isinstance(data, bytes):
        raise TypeError('data need bytes')
    replace_one_b = replace_one.encode('utf-8')
    replace_two_b = replace_two.encode('utf-8')
    data = data.replace(replace_one_b, b'z').replace(replace_two_b, b'2')
    return base64.decodebytes(data).decode('utf-8')
if __name__ == '__main__':
    result = encode('zhangsan')  # 加密
    print(result)
    print(decode(result.encode()))  # 解密