python jwt用装饰器实现,并进行DES加密

"""
"""

from functools import wraps
import jwt
import datetime

from pyDes import des, PAD_PKCS5

from flask import request
SECRECT_KEY = 'secret'
import base64
KEY='c8eahd59'
# from rest_framework.response import Response

def checkToken():
    def decorated(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            try:

                # token=base64.b64decode(request.headers['token'])
                token = b'@\xc1\xcb\xd9\xaf\xf6\x86\x9aH\xf2(\xeeN\xba\x0b\x11F+\xee\xc1\xd7\xdb\x92\x9d-\x9e .\xd3\xa4@\xf5\xab\xc7\xa5\xdc\x18U\x04\xd6\xdb\x863\xbc<\xde\'\x08\x87\xc4S\xb6~\xa3]\x1a\xba;n\xd2\xe1;\xa5W\x02>3\x8a9\x8c\xab<9SS\xfe\xa4\xdb\x1cI\xcf\x1e_L#Y\x87\xb79\xd7BB\x1a\xa1\xfc\x94\xf4\xbaf\x10c)qq\xef\xdcJ}\xd0)\xa1\x8d^Syj\xa7\xe7\x91s\x95\xe3K\x08S\x94mt\xf5\xa5\xd8%!\xb08\xf9"\xc3\xdei\x17\xe8\xd8\x1a\xd3\xaa\x9c7\x10|gq'
                token = des_descrypt(token)
                print('token 是:', token)
                decoded = jwt.decode(token, SECRECT_KEY, algorithms=['HS256'])
                print('解析出来token', decoded)
                return func()
            except jwt.ExpiredSignatureError as err:
                print("erroing.................",err)
                decoded = {"error_msg": "is timeout !!", "some": None}
                # return '{"code":"004"}'+request.url
            except Exception:
                decoded = {"error_msg": "noknow exception!!", "some": None}
                # return '{"code":"004"}'+request.url
            return (decoded)
        return wrapper
    return decorated


def des_descrypt(s):
    """
    DES 解密
    :param s: 加密后的字符串,16进制
    :return:  解密后的字符串
    """
    secret_key = KEY
    k = des(secret_key)
    de = k.decrypt(s, padmode=PAD_PKCS5).decode("utf-8")
    # k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    # de = k.decrypt(s, padmode=PAD_PKCS5)
    return de


def DesEncrypt(st):
    # Des加密
    Des_Key =KEY
    k = des(Des_Key)
    EncryptStr = k.encrypt(st, padmode=PAD_PKCS5)
    return EncryptStr


def jwtEncoding(some):
    datetimeInt = datetime.datetime.utcnow() + datetime.timedelta(seconds=180)
    # print(datetimeInt)
    option = {
        'iss': 'jobapp.com',
        'exp': datetimeInt,
        # 'aud': 'webkit',
        'claim':some
    }
    encoded2 = jwt.encode(option, SECRECT_KEY, algorithm='HS256')
    # print(encoded2.decode())
    return DesEncrypt(encoded2.decode())


@checkToken()
def cc():
    return True

def heihei():
    try:
        print(1/0)
    except Exception:
        return False
    finally:
        print("JHeng")

if __name__ == '__main__':
    # res=jwtEncoding("889")
    # print(res)
    # re = cc()
    # print(re)
    print(heihei())


你可能感兴趣的:(python)