[Django] Use itsdangerous to encrypt json data to generate token

Sometimes we need to send some information to the front end, and then the front end will send it back. If we encounter sensitive information, it will be exposed, so we need to encrypt it into a token, and then decrypt it when the front end sends it back. We can use itsdangerous module for encryption and decryption operations

1. Install itsdangerous

pip install itsdangerous

2. Simple to use

In fact, itsdangerous can be used in many ways. We only use the method of encrypting and decrypting JSON. We need to use the dumps() and loads() methods of the TimedJSONWebSignatureSerializer class.

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
# 传入秘钥和有效期(秒)
serializer = Serializer('abcd',300)  
token = serializer.dumps({
    
    'mobole':'13978488888'}).decode()
print(token)  # 结果:eyJpYXQiOjE1OTk4MDEzNjEsImFsZyI6IkhTNTEyIiwiZXhwIjoxNTk5...

# serializer = Serializer('1234',300)  假如传入的秘钥不正确就会报错
try:
    data = serializer.loads(token)
    print(data)  # 结果:{'mobole': '13978488888'}
except Exception as e:
    print('解密失败')
    

3. Package into classes

The advantage of encapsulation is that it is convenient to call and makes the code business code more concise. Let’s simply encapsulate it here.

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings


class SecretOauth(object):
    def __init__(self):
        # self.serializer = Serializer(secret_key='abcd',expires_in=300)

        # 这里使用django配置文件里提供的秘钥
        self.serializer = Serializer(secret_key=settings.SECRET_KEY,expires_in=300)

    # 加密
    def dumps(self,content_dict):
        token = self.serializer.dumps(content_dict).decode()
        return token

    # 解密
    def loads(self,token):
        try:
            content_dict = self.serializer.loads(token)
        except Exception as e:
            return None
        return content_dict

if __name__ == '__main__':

    res = SecretOauth().dumps(content_dict={
    
    'mobile':'13978488888'})
    print('加密后:', res)
    res2 = SecretOauth().loads(res)
    print('解密后:', res2)
    print(res2.get('mobile'))

Guess you like

Origin blog.csdn.net/qq_39147299/article/details/108532467