Django 1.8 official document translation: 8-5 encrypted signature


Encrypted signature

The golden rule of web application security is never trust data from untrusted sources. Sometimes it’s very convenient to transfer data through untrusted media. The value after the password signature can be passed through an untrusted way, which is secure, because any tampering will be detected.

Django provides the underlying API for signature and the upper API for setting and reading signed cookies. They are one of the most commonly used signature tools in web applications.

You may find that signatures are very useful for the following things:

  • Generate a URL for “reset my account” and send it to users who have lost their password.

  • Ensure that data stored in hidden form fields is not tampered with,

  • Generate a one-time secret URL to temporarily allow access to protected resources, such as user paid download files.

Protect secret_ KEY

When you use startproject to create a new Django project, the automatically generated settings. Py file gets a random secret_ Key value. This value is the key to protect the signature data – it is very important, you must keep it properly, otherwise the attacker will use it to generate his own signature value.

Using the underlying API

Django’s signature method is stored indjango.core.signingmodular. First, create aSignerTo sign a value:

>>> from django.core.signing import Signer
>>> signer = Signer()
>>> value = signer.sign('My string')
>>> value
'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'

The signature is appended to the end of the string, followed by a colon. You can use itunsignMethod to get the original value:

>>> original = signer.unsign(value)
>>> original
'My string'

If the signature or value changes in any way, adjango.core.signing.BadSignatureException:

>>> from django.core import signing
>>> value += 'm'
>>> try:
...    original = signer.unsign(value)
... except signing.BadSignature:
...    print("Tampering detected!")

In general,SignerClass usageSECRET_KEYSet to generate the signature. You can do this bySignerThe constructor passes a different key to use it:

>>> signer = Signer('my-other-secret')
>>> value = signer.sign('My string')
>>> value
'My string:EkfQJafvGyiofrdGnuthdxImIJw'

class Signer(key=None, sep=':', salt=None)[source]

Return asigner, which useskeyTo generate the signature and use thesepTo split the values.sepCannot be URL safe Base64 alphabet(]The character in the. The alphabet contains numbers, letters, hyphens, and underscores.

Using the salt parameter

If you don’t want to generate the same signature hash for each particular string, you can use theSignerClasssaltParameters. usesaltThe parameter is used with bothSECRET_KEYInitialize the signature hash function:

>>> signer = Signer()
>>> signer.sign('My string')
'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'
>>> signer = Signer(salt='extra')
>>> signer.sign('My string')
'My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw'
>>> signer.unsign('My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw')
'My string'

Use in this waysaltDifferent signatures are placed in different namespace. From a single namespace (a specificsaltValue) cannot be used to verify the same plain text string in different namespace. Different namespace uses differentsaltset up. This is to prevent an attacker from using the signed string generated in the code in one place as a way to use a different stringsaltTo generate (and verify) the input of another code for the signature.

It’s not like yoursSECRET_KEYYoursaltParameters can be kept secret.

Verify values with timestamps

TimestampSigneryesSignerIt appends a signed timestamp to the value. This allows you to confirm whether a signed value has been created in a specific period of time

>>> from datetime import timedelta
>>> from django.core.signing import TimestampSigner
>>> signer = TimestampSigner()
>>> value = signer.sign('hello')
>>> value
>>> signer.unsign(value)
>>> signer.unsign(value, max_age=10)
SignatureExpired: Signature age 15.5289158821 > 10 seconds
>>> signer.unsign(value, max_age=20)
>>> signer.unsign(value, max_age=timedelta(seconds=20))

class TimestampSigner(key=None, sep=':', salt=None)[source]


autographvalueAnd attach the current timestamp.

unsign(value, max_age=None)[source]

inspectvalueIs it less thanmax_ageSigned seconds ago, if not thrownSignatureExpiredAbnormal.max_ageParameter takes an integer ordatetime.timedeltaObject.

Changed in Django 1.8:

Before that, max_ The age parameter accepts only integers.

Protect complex data structures

If you want to protect a list, tuple, or dictionary, you can use thedumpsandloadsFunction. They mimic pythonpickleModule, but used behind the scenesJSONSerialization.JSONTo make sure that even yourSECRET_KEYIf it is stolen, the attacker can’t take advantage of itpickleTo execute any command in the following format:

>>> from django.core import signing
>>> value = signing.dumps({"foo": "bar"})
>>> value
>>> signing.loads(value)
{'foo': 'bar'}

becauseJSONIf you pass in a tuple, you willsigning.loads(object)Get a list:

>>> from django.core import signing
>>> value = signing.dumps(('a','b','c'))
>>> signing.loads(value)
['a', 'b', 'c']

dumps(obj, key=None, salt='django.core.signing', compress=False)[source]

Return URL security, SHA1 signed Base64 compressed JSON string. Serialized objects usingTimestampSignerCome and sign.

loads(string, key=None, salt='django.core.signing', max_age=None)[source]

dumps()If the signature fails, it will be thrownBadSignatureAbnormal. If providedmax_ageIt is checked (in seconds).

translator:Django document collaborative translation teamOriginal text:Cryptographic signing

This paper is based onCC BY-NC-SA 3.0Please keep the author’s signature and the source of the article.

Django document collaborative translation teamWe are short of staff. Interested friends can join us. It is totally public welfare. Communication group: 467338606.

Recommended Today

The use of springboot Ajax

Ajax overview What is Ajax? data Ajax application scenarios? project Commodity system. Evaluation system. Map system. ….. Ajax can only send and retrieve the necessary data to the server, and use JavaScript to process the response from the server on the client side. data But Ajax technology also has disadvantages, the biggest disadvantage is that […]