欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python对token的有效期校验简单例子

程序员文章站 2022-06-10 20:46:09
...
# -*- coding: utf-8 -*-
import hashlib


#待加密内容
strdata="xiaojingjiaaseafe16516506ng"

h1=hashlib.md5()
h1.update(strdata.encode(encoding='utf-8'))

strdata_tomd5=h1.hexdigest()


print("原始内容:",strdata,",加密后:",strdata_tomd5)



import time
import base64
import hmac

#生产token
def generate_token(key, expire=3600):
    r'''
        @Args:
            key: str (用户给定的key,需要用户保存以便之后验证token,每次产生token时的key 都可以是同一个key)
            expire: int(最大有效时间,单位为s)
        @Return:
            state: str
    '''
    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")

#验证token
def certify_token(key, token):
    r'''
        @Args:
            key: str
            token: str
        @Returns:
            boolean
    '''
    token_str = base64.urlsafe_b64decode(token).decode('utf-8')
    token_list = token_str.split(':')
    if len(token_list) != 2:
        return False
    ts_str = token_list[0]
    if float(ts_str) < time.time():
        # token expired
        return False
    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:
        # token certification failed
        return False
    # token certification success
    return True


key="xiaojingjing"
print("key:",key)
user_token=generate_token(key=key)

print("加密后:",user_token)
user_de=certify_token(key=key,token=user_token)
print("验证结果:",user_de)

key="xiaoqingqing"
user_de=certify_token(key=key,token=user_token)
print("验证结果:",user_de)