zoukankan      html  css  js  c++  java
  • python Token加密解密方式

    一、安装包

    pip install pyjwt

    二、代码逻辑实现

    import time
    import jwt
    
    class Token(object):
    
        def __init__(self):
            pass
    
        @classmethod
        def encrpyt_token(cls,username,uuid,exptime=None,secret=None):
            """
            iss:该JWT的签发者,是否使用是可以选择的。
            sub:该JWT所面向的用户,是否使用是可选的。
            aud:接收该JWT的一方,是否使用是可选的。
            exp(expires):什么时候过期,是一个UNIX的时间戳,是否使用是可选的。默认设置为:30分钟
            iat(issued at):在什么时候签发UNIX时间,是否使用是可选的。
            nbf(not before):如果当前时间在nbf的时间之前,则Token不被接受,一般都会留几分钟,是否使用是可选的。
            :return:
            """
            if not exptime:
                exptime = time.time() + 60*30
    
            if not secret:
                secret = 'iam'
    
            payloads = {
                'iss': 'IAM JWT Builder',
                'iat': time.time(),
                'username':username,
                'uuid':str(uuid),
                "exp": exptime
            }
            encoded_jwt = jwt.encode(payloads, secret, algorithm='HS256')
            return encoded_jwt
    
        @classmethod
        def decrypt_token(cls,token,secret=None):
            """
            encoded_jwt = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJJQU0gSldUIEJ1aWxkZXIiLCJpYXQiOjE1ODQzNDA0NjkuOTE5ODQxLCJ1c2VybmFtZSI6Inl1bGlhbmh1aTEiLCJ1dWlkIjoiOTQwYjBhZTgtNWEwNi0xMWVhLWEzNWItZjEwNWMyOGI2NDE2IiwiZXhwIjoxNTg0MzQyMjY5LjkxOTg0MX0.zITnwaB0zsuyO1kiyYBG5IFWEy5FewDGSJAj1eJ-uEg'
            decode_jwt = jwt.decode(encoded_jwt, 'iam', algorithms=['HS256'])
            print('decode_jwt',decode_jwt)
            :param token:
            :param secret:
            :return:
            """
            try:
                if not secret:
                    secret = 'iam'
                decode_jwt = jwt.decode(token, secret, algorithms=['HS256'])
    
                return decode_jwt
            except jwt.exceptions.InvalidSignatureError as e:
                return {'error':'Signature verification failed'}
    
    authToken = Token()
  • 相关阅读:
    指针、字符串、数组操作
    字符串转换为数字(str2int)
    新的,开始。
    Hello, World.
    Go语言趣学指南lesson1
    hdoj2058
    poj2378
    hdoj1233
    poj2398
    hdoj1392
  • 原文地址:https://www.cnblogs.com/supery007/p/12504914.html
Copyright © 2011-2022 走看看