Sometimes we need some important data encryption, such as the application signature, qq
authorization openid
and so on.
Security Encryption
Here are some itsdangerous
which may be encrypted sensitive data bit, it can pip
be installed directly. The following are used in django
common in the encryption.
from itsdangerous.jws import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings
def dumps(dict, expires):
'''
将字典加密,返回加密字符串
:param dict:字典
:param expires:过期时间
:return:字符串
'''
serializer = Serializer(settings.SECRET_KEY, expires_in=expires)
json_str = serializer.dumps(dict).decode()
return json_str复制代码
The above key is encrypted using the application, the data is generally not exposed to, but we also set an expiration period, all theoretically can not break. If you want to decrypt ourselves, take the following way. This can be applied to verify some of the sensitive data.
def loads(json_str, expires):
'''
将加密字符串解密
:param json_str: 加密字符串
:return: 字典
'''
serializer = Serializer(settings.SECRET_KEY, expires_in=expires)
try:
dict = serializer.loads(json_str)
except:
# 如果字符串被修改过,或超期,会抛异常
return None
else:
return dict复制代码
Symmetric encryption
base64 is a symmetric encryption method, is reversible. For some less important data encryption.
import pickle
import base64
def dumps(dict):
'''将字典转换成bytes'''
json_bytes = pickle.dumps(dict)
# 加密
json_secret = base64.b64encode(json_bytes)
# 转字符串
json_str = json_secret.decode()
return json_str
def loads(json_str):
'''字符串转bytes'''
json_secret = json_str.encode()
# 解密
json_bytes = base64.b64decode(json_secret)
# 转字典
json_dict = pickle.loads(json_bytes)
return json_dict复制代码
base64 encryption and decryption parameters are passed bytes, if the dictionary to dict
encryption, using pickle
modules to be converted to bytes type before proceeding.
Reproduced in: https: //juejin.im/post/5d03c50f51882562fb138827