import time
import base64
import hmac
# 密钥
KEY = "ABCD1234!@#$"
def generate_token(key=KEY, expire=3600):
"""
:param key: 密钥
:param expire: 过期时长 单位为秒
:return: token
"""
ts_str = str(time.time() + expire) # 确定有效时间
ts_byte = ts_str.encode("utf-8")
sha1_tshexstr = hmac.new(key.encode("utf-8"), ts_byte, 'sha1').hexdigest()
token = ts_str + ':' + sha1_tshexstr
b64_token = base64.urlsafe_b64encode(token.encode("utf-8"))
return b64_token.decode("utf-8")
def verify_token(auth_token):
if not auth_token:
return "token expired"
token_str = base64.urlsafe_b64decode(auth_token).decode('utf-8')
token_list = token_str.split(':')
if len(token_list) != 2:
return "token expired"
ts_str = token_list[0]
if float(ts_str) < time.time(): # 判断有效时间
return "token expired"
known_sha1_tsstr = token_list[1]
sha1 = hmac.new(KEY.encode("utf-8"), ts_str.encode('utf-8'), 'sha1')
calc_sha1_tsstr = sha1.hexdigest()
if calc_sha1_tsstr != known_sha1_tsstr:
return "token expired"
return "token ok!"
Python 用于身份验证的 HMAC 模块
最新推荐文章于 2024-06-05 07:15:58 发布