1024programmer Java Django from scratch 11 encrypt data based on timestamp

Django from scratch 11 encrypt data based on timestamp

Django comes with an encryption method, signer, to encrypt the data

Generally, this method is used to retrieve the account and password email, or set the token

class TimestampSigner(Signer):def timestamp(self):return baseconv.base62.encode(int(time.time()))def sign(self, value):value = '%s%s%s' % (value, self.sep, self.timestamp())return super().sign (value)def unsign(self, value, max_age=None):“””Retrieve original value and check it wasn’t signed more than max_age seconds ago.“””result = super().unsign( value)value, timestamp = result.rsplit(self.sep, 1)timestamp = baseconv.base62.decode(timestamp) if max_age is not None:if isinstance(max_age, datetime .timedelta):max_age = max_age.total_seconds()# Check timestamp is not older than max_ageage &# 61; time.time() – timestampif age > max_age:raise SignatureExpired( span>'Signature age %s > %s seconds' % (age, max_age))return value

This is the source code in the Django document. You can see that it is inherited from the signer class. The sign function adds the current timestamp to the input data. Perform an encryption

Unsign verifies whether the encrypted data is out of date, obtains the timestamp of the incoming encrypted data, and converts the max_age time in the function to a time format comparison. If the current time minus the time of the encrypted data is greater than the setting If the specified time is exceeded, an exception will be thrown, otherwise the correct value will be returned

But there is a big problem, that is, the encrypted data will be displayed. For example, the encrypted data {'name':' Xiao Ming'} will be displayed as' {'name':'Xiao Ming'}:fszfdfyhYRTCFVDRSVG15R1X32B' This obviously does not work


Later, I searched online and found that the sign class contains serialization for encryption and can add encryption. Time control

Actually Encrypt the timestamp of the TimestampSigner class above and return a string of encrypted characters. By default, the current timestamp is used for time authentication. Unlike flask, which can confirm the expiration time when encrypting,

Can be saved to COOKIES and go to the next page You need to verify and use this verification (ps has been stuck in COOKIES for a long time. I thought that the cookeis was not passed over and it was always empty. It turns out that HttpResponse needs to be set…)


Decrypt the sign value

It is also the timestamp decryption of TimestampSigner. The source code is as follows

Key and sigin encryption are not set by default, so keep it simple first

There is a parameter max_age (used to compare time) unsign decryption source code

For example, if you perform an encryption at 1:10, and the encryption sign value contains the time of 1:10, use unsign decryption input max_age=60 The value is seconds If not set, it will exist permanently

During the decryption process, the time will be formatted by comparing the current decryption time minus Encrypted time: If the subtracted time is greater than the set expiration time, an exception will be thrown, otherwise the decrypted value will be returned


p>

So my code is

Encryption

from datetime import datetime
from django.core import signingdef set_sign(request):value = signing.dumps({'user' :1254,'name':'xiaomingXiaoming'})print(value)request.COOKIES[ 'sign'] = valuereq = HttpResponse('Get sign value successfully')req.set_COOKIE(&#39 ;sign',value)return req

Decryption

def get_sign(request):value = request.COOKIES.get(& #39;sign')print(value)s &# 61; 'No sign'if value: span>try:s = signing.loads(value,max_age=20)  # Set expiration timeprint (s,datetime.now())print(type(s))       # What format is returned during encryptionexcept:print('sign expired&#39 ;,datetime.now())s = 'sign expired&#39 ;return HttpResponse(s)

Result

Get the non-expired sign and get the result Enter dict to get dict

Compare the decryption time expiration results

The set 20-second expiration time is set to 20:42:23. The time to obtain the sign is 20:43:38. Even if the sign value can be obtained, the decryption error will occur

Redirect: https://www.cnblogs.com/zengxm/p/11323744.html

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/734676

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索