5 .. module:: django.core.signing
6 :synopsis: Django's signing framework.
10 The golden rule of Web application security is to never trust data from
11 untrusted sources. Sometimes it can be useful to pass data through an
12 untrusted medium. Cryptographically signed values can be passed through an
13 untrusted channel safe in the knowledge that any tampering will be detected.
15 Django provides both a low-level API for signing values and a high-level API
16 for setting and reading signed cookies, one of the most common uses of
17 signing in Web applications.
19 You may also find signing useful for the following:
21 * Generating "recover my account" URLs for sending to users who have
24 * Ensuring data stored in hidden form fields has not been tampered with.
26 * Generating one-time secret URLs for allowing temporary access to a
27 protected resource, for example a downloadable file that a user has
30 Protecting the SECRET_KEY
31 =========================
33 When you create a new Django project using :djadmin:`startproject`, the
34 ``settings.py`` file is generated automatically and gets a random
35 :setting:`SECRET_KEY` value. This value is the key to securing signed
36 data -- it is vital you keep this secure, or attackers could use it to
37 generate their own signed values.
39 Using the low-level API
40 =======================
44 Django's signing methods live in the ``django.core.signing`` module.
45 To sign a value, first instantiate a ``Signer`` instance::
47 >>> from django.core.signing import Signer
49 >>> value = signer.sign('My string')
51 'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'
53 The signature is appended to the end of the string, following the colon.
54 You can retrieve the original value using the ``unsign`` method::
56 >>> original = signer.unsign(value)
60 If the signature or value have been altered in any way, a
61 ``django.core.signing.BadSignature`` exception will be raised::
65 ... original = signer.unsign(value)
66 ... except signing.BadSignature:
67 ... print "Tampering detected!"
69 By default, the ``Signer`` class uses the :setting:`SECRET_KEY` setting to
70 generate signatures. You can use a different secret by passing it to the
71 ``Signer`` constructor::
73 >>> signer = Signer('my-other-secret')
74 >>> value = signer.sign('My string')
76 'My string:EkfQJafvGyiofrdGnuthdxImIJw'
78 Using the salt argument
79 -----------------------
81 If you do not wish for every occurrence of a particular string to have the same
82 signature hash, you can use the optional ``salt`` argument to the ``Signer``
83 class. Using a salt will seed the signing hash function with both the salt and
84 your :setting:`SECRET_KEY`::
87 >>> signer.sign('My string')
88 'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'
89 >>> signer = Signer(salt='extra')
90 >>> signer.sign('My string')
91 'My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw'
92 >>> signer.unsign('My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw')
95 Using salt in this way puts the different signatures into different
96 namespaces. A signature that comes from one namespace (a particular salt
97 value) cannot be used to validate the same plaintext string in a different
98 namespace that is using a different salt setting. The result is to prevent an
99 attacker from using a signed string generated in one place in the code as input
100 to another piece of code that is generating (and verifying) signatures using a
103 Unlike your :setting:`SECRET_KEY`, your salt argument does not need to stay
106 Verifying timestamped values
107 ----------------------------
109 .. class:: TimestampSigner
111 ``TimestampSigner`` is a subclass of :class:`~Signer` that appends a signed
112 timestamp to the value. This allows you to confirm that a signed value was
113 created within a specified period of time::
115 >>> from django.core.signing import TimestampSigner
116 >>> signer = TimestampSigner()
117 >>> value = signer.sign('hello')
119 'hello:1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c'
120 >>> signer.unsign(value)
122 >>> signer.unsign(value, max_age=10)
124 SignatureExpired: Signature age 15.5289158821 > 10 seconds
125 >>> signer.unsign(value, max_age=20)
128 Protecting complex data structures
129 ----------------------------------
131 If you wish to protect a list, tuple or dictionary you can do so using the
132 signing module's ``dumps`` and ``loads`` functions. These imitate Python's
133 pickle module, but use JSON serialization under the hood. JSON ensures that
134 even if your :setting:`SECRET_KEY` is stolen an attacker will not be able
135 to execute arbitrary commands by exploiting the pickle format.::
137 >>> from django.core import signing
138 >>> value = signing.dumps({"foo": "bar"})
140 'eyJmb28iOiJiYXIifQ:1NMg1b:zGcDE4-TCkaeGzLeW9UQwZesciI'
141 >>> signing.loads(value)
144 .. function:: dumps(obj, key=None, salt='django.core.signing', compress=False)
146 Returns URL-safe, sha1 signed base64 compressed JSON string.
148 .. function:: loads(string, key=None, salt='django.core.signing', max_age=None)
150 Reverse of dumps(), raises ``BadSignature`` if signature fails.