目录
- hashlib模块介绍
- hashlib模块中的常用方法
- base64模块介绍
- base64模块的常用方法
hashlib介绍
hashlib模块中的常用方法
hashobj = hashlib.md5(b’hello’)
result = hashobj. hexdigest()
print(result)
>> '6b8bfd346d1dcc17e6940aa59b9c4fa6864064a8'
实战
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/8/23 21:40
# @Author : InsaneLoafer
# @File : package_hashlib.py
import hashlib
import time
base_sign = 'insane'
def custom():
a_timestamp = int(time.time())
_token = '%s%s' % (base_sign, a_timestamp)
hashobj = hashlib.sha1(_token.encode('utf-8'))
a_token = hashobj.hexdigest() # 生成16进制加密串
return a_token, a_timestamp
def b_service_check(token, timestamp):
_token = '%s%s' % (base_sign, timestamp)
b_token = hashlib.sha1(_token.encode('utf-8')).hexdigest()
if token == b_token:
return True
else:
return False
if __name__ == '__main__':
need_help_token, timestamp = custom()
result = b_service_check(need_help_token, timestamp)
if result == True:
print('a合法,b服务可以进行帮助')
else:
print('a不合法,b不可进行帮助')
a合法,b服务可以进行帮助
Process finished with exit code 0
base64包介绍
base64常用方法
函数名 |
参数 |
介绍 |
举例 |
返回值 |
encodingstring |
Byte |
进行base64加密 |
base64.encodingstring(b'py') |
Byte |
decodingstring |
Byte |
对base64解密 |
base64.decodingstring(b'eGlhb211\n') |
Byte |
encodebytes |
Byte |
进行base64加密 |
base64.encodebytes(b'py') |
Byte |
decodebytes |
Byte |
对base64解密 |
base64.decodebytes(b'eGlhb311\n') |
Byte |
实战
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/8/23 21:57
# @Author : InsaneLoafer
# @File : package_base64.py
import base64
repalce_one = '%'
repalce_two = '$'
def encode(data):
if isinstance(data, str):
data = data.encode('utf-8')
elif isinstance(data, bytes):
data = data
else:
raise TypeError('data need bytes or str')
_data = base64.encodebytes(data).decode('utf-8')
print(_data)
_data = _data.replace('a', repalce_one).replace('8', repalce_two)
return _data
def decode(data):
if not isinstance(data, bytes):
raise TypeError('data need to be bytes')
repalce_one_b = repalce_one.encode('utf-8')
repalce_two_b = repalce_two.encode('utf-8')
data = data.replace(repalce_one_b, b'a').replace(repalce_two_b, b'8')
return base64.decodebytes(data).decode('utf-8')
if __name__ == '__main__':
result = encode('123hello')
print(result)
new_result = decode(result.encode('utf-8'))
print(new_result)
MTIzaGVsbG8=
MTIz%GVsbG$=
123hello
Process finished with exit code 0