Django 6.1.3

5.3 Security by default

Cryptographic signing and key rotation

How do Signer and TimestampSigner derive distinct keys via salts, and how does SECRET_KEY_FALLBACKS let you rotate keys without logging every user out?

Whenever Django sends data through an untrusted client and expects to read it back intact — signed cookies, CookieStorage messages, form-wizard state, or short-lived invite links — it relies on django/core/signing.py. Note what signing does and does not do: it provides integrity and authenticity (HMAC), never confidentiality. Anyone can base64-decode a django.core.signing.dumps payload and read every field inside; they simply cannot forge or alter a single byte without knowing SECRET_KEY.

The module centers on four concepts: Signer, TimestampSigner, domain-separating key salt derivation via salted_hmac, and SECRET_KEY_FALLBACKS for seamless key rotation.

Domain separation via salted_hmac and key salts

Open salted_hmac:

key_salt = force_bytes(key_salt)
secret = force_bytes(secret)
hasher = getattr(hashlib, algorithm)
key = hasher(key_salt + secret).digest()
return hmac.new(key, msg=force_bytes(value), digestmod=hasher)

Instead of feeding SECRET_KEY directly into hmac.new, Django derives a sub-key for every caller by hashing key_salt + secret with the chosen digest ("sha256" by default in Signer, Signer).

Why does key salt isolation matter so much? Suppose one endpoint signs "ada" to produce an email-confirmation link and another endpoint signs "ada" to produce an admin-impersonation cookie. If both used the same key, an attacker could take the valid email-confirmation signature for "ada" and replay it as an admin cookie! Giving every feature a distinct salt (for example "desk.invite" vs "desk.unsubscribe") produces completely independent derived HMAC keys from a single SECRET_KEY.

Notice two sharp details in django/core/signing.py and django/utils/crypto.py on Django 6.1.3:

  1. Signer.signature appends "signer" (self.salt + "signer") and explicitly passes algorithm=self.algorithm ("sha256" by default). Meanwhile, direct calls to salted_hmac or base64_hmac without an explicit algorithm= keyword still default to "sha1" for backwards compatibility and emit RemovedInDjango2028Warning (switching to "sha256" in Django 2028).
  2. Signer.__init__ rejects any separator matching _SEP_UNSAFE (^[A-z0-9-_=]*$) so the separator (":" by default) can never collide with URL-safe base64 characters in the signature, and Signer.unsign uses str.rsplit(self.sep, 1) so the payload itself is free to contain colons.

TimestampSigner, base-62 expiry, and SECRET_KEY_FALLBACKS

TimestampSigner subclasses Signer to embed a compact Unix timestamp inside the signed payload:

  1. TimestampSigner.sign encodes int(time.time()) in base-62 (b62_encode, 6 characters for current epoch timestamps like "1vNYyu"), appends ":<timestamp>" to the value, and delegates to Signer.sign — so the timestamp itself is covered by the HMAC and cannot be rolled forward by an attacker.
  2. TimestampSigner.unsign(value, max_age=...) first verifies the signature via super().unsign(value) (raising BadSignature on forgery), splits off and decodes the timestamp, and then checks time.time() - timestamp > max_age — raising SignatureExpired (a subclass of BadSignature) if the token is stale.

Now look at Signer.unsign (lines 246–253) — the entire key-rotation engine is four lines of Python:

value, sig = signed_value.rsplit(self.sep, 1)
for key in [self.key, *self.fallback_keys]:
    if constant_time_compare(sig, self.signature(value, key)):
        return value
raise BadSignature('Signature "%s" does not match' % sig)

Signing always uses the primary SECRET_KEY. Verification tries [self.key, *self.fallback_keys] in order and returns on the first constant-time match. That lets you rotate keys cleanly in three deploys: move the old key into SECRET_KEY_FALLBACKS and install a new SECRET_KEY (all existing signed cookies and sessions stay valid while new writes adopt the new key); wait out your cookie/session lifetime; remove the retired key from SECRET_KEY_FALLBACKS.

That simplicity carries a real, measurable cost: every fallback key adds another full salted_hmac derivation and comparison whenever a token was signed by an older key — or whenever an attacker sends forged signatures!

Figure 5.3 Every latency bar is parsed from ch05-bench and every salt string from ch05-security. Verification scales strictly linearly with fallback list depth (6.08 us at 1 HMAC to 35.95 us at 6 HMACs, 5.92x), and every forged signature pays the full worst-case scan across all keys.

Watch the entire rotation lifecycle, timestamp expiry, Django 6.1 v2 cookie salt fix, and compressed-object protection run live:

Recorded on Django 6.1.3 ch05-security script
Signer, TimestampSigner, SECRET_KEY_FALLBACKS, and Django 6.1 cookie v2 salt
  Signer(key-v1, salt='desk.invite').sign('ada') -> 'ada:MAN58VCXNviPRcJtIpGmHD5ouSrhlIhhzvUbAI_VCzM'
  rotated Signer(key-v2, fallback=[key-v1]).unsign(tok_v1) -> 'ada'
  rotated Signer signs new values with key-v2 (tok_v2 != tok_v1): True
  wrong salt replay -> BadSignature: Signature "MAN58VCXNviPRcJtIpGmHD5ouSrhlIhhzvUbAI_VCzM" does not match
  after retiring key-v1 -> BadSignature: Signature "MAN58VCXNviPRcJtIpGmHD5ouSrhlIhhzvUbAI_VCzM" does not match
  TimestampSigner at t0=1764000000: token='edition-42:1vNYyu:yLPNeIM8-Ux5s9EWrc6TeCqT6UNXhiahQrk9VbI8tOc'; unsign(+30s, max_age=60) -> 'edition-42'
  TimestampSigner unsign(+90s, max_age=60) -> SignatureExpired: Signature age 90.0 > 60 seconds
  legacy cookie salt collision: ('ab','c')='abc' == ('a','bc')='abc' -> True
  Django 6.1 v2 cookie salt:    ('ab','c')='django.http.cookies.v2:1:cab' != ('a','bc')='django.http.cookies.v2:2:bca' -> True
  compressed dumps starts with '.': True; tampered payload -> BadSignature

Two subtle hardening details in signing.py

Look closely at the last three lines of that recording — both solve real cryptographic edge cases:

  1. Django 6.1’s length-prefixed cookie v2 salt (_cookie_signer_salt, lines 122–146): Historically, HttpResponseBase.set_signed_cookie and HttpRequest.get_signed_cookie derived their salt by plain concatenation (cookie_name + salt). That meant cookie "ab" with salt "c" and cookie "a" with salt "bc" both collapsed to "abc" — sharing the exact same derived HMAC key! Django 6.1 replaces that with _cookie_signer_salt: f"django.http.cookies.v2:{len(salt)}:{salt}{cookie_name}". Because the length of salt is explicitly encoded before the characters, ("ab", "c") and ("a", "bc") can never collide ("django.http.cookies.v2:1:cab" vs "django.http.cookies.v2:2:bca"). During upgrades, _unsign_cookie falls back transparently to _cookie_signer_legacy_salt when SIGNED_COOKIE_LEGACY_SALT_FALLBACK is True — unless the failure was SignatureExpired (an expired v2 cookie must never be accepted under a legacy salt).
  2. Zip-bomb defense on compressed payloads (Signer.sign_object / Signer.unsign_object, lines 255–291): When django.core.signing.dumps (dumps, with compress=True) compresses JSON with zlib.compress, it prepends a literal "." to the base64 payload before computing the signature. On unsign_object, Django verifies the HMAC before it ever inspects base64d[:1] == b"." or invokes zlib.decompress. An unauthenticated attacker therefore cannot feed a crafted 10 KB deflate bomb that expands into 10 GB of RAM.

Where cryptographic signing leaks

Signing protects data that crosses the wire back to Django. Next, we inspect the browser-enforced policy layer that Django 6.0 brought directly into core: Content Security Policy and browser headers.