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/. Note what signing does and does not do: it provides integrity and authenticity (HMAC), never confidentiality. Anyone can base64-decode a django 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) produces completely independent derived HMAC keys from a single SECRET_KEY.
Notice two sharp details in django/ and django/ on Django 6.1.3:
Signer.signatureappends"signer"(self) and explicitly passes.salt + "signer" algorithm=self(.algorithm "sha256"by default). Meanwhile, direct calls tosalted_hmacorbase64_hmacwithout an explicitalgorithm=keyword still default to"sha1"for backwards compatibility and emitRemovedInDjango2028Warning(switching to"sha256"in Django 2028).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, andSigner.unsignusesstrso the payload itself is free to contain colons..rsplit(self .sep, 1)
TimestampSigner, base-62 expiry, and SECRET_KEY_FALLBACKS
TimestampSigner subclasses Signer to embed a compact Unix timestamp inside the signed payload:
TimestampSignerencodes.sign int(time.time())in base-62 (b62_encode, 6 characters for current epoch timestamps like"1vNYyu"), appends":<timestamp>"to the value, and delegates toSigner.sign— so the timestamp itself is covered by the HMAC and cannot be rolled forward by an attacker.TimestampSignerfirst verifies the signature via.unsign(value, max_age=...) super().unsign(value)(raisingBadSignatureon forgery), splits off and decodes the timestamp, and then checkstime— raising.time() - timestamp > max_age SignatureExpired(a subclass ofBadSignature) 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 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!
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:
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:
- Django
6.1’s length-prefixed cookie v2 salt (_cookie_signer_salt, lines 122–146): Historically,HttpResponseBaseand.set_signed_cookie HttpRequestderived their salt by plain concatenation (.get_signed_cookie 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! Django6.1replaces that with_cookie_signer_salt:f"django. Because the length of.http .cookies .v2: {len(salt)}: {salt}{cookie_name}" saltis explicitly encoded before the characters,("ab", "c")and("a", "bc")can never collide ("djangovs.http .cookies .v2: 1: cab" "django). During upgrades,.http .cookies .v2: 2: bca" _unsign_cookiefalls back transparently to_cookie_signer_legacy_saltwhenSIGNED_COOKIE_LEGACY_SALT_FALLBACKisTrue— unless the failure wasSignatureExpired(an expired v2 cookie must never be accepted under a legacy salt). - Zip-bomb defense on compressed payloads (
Signer/.sign_object Signer, lines 255–291): When.unsign_object django(.core .signing .dumps dumps, withcompress=True) compresses JSON withzlib.compress, it prepends a literal"."to the base64 payload before computing the signature. Onunsign_object, Django verifies the HMAC before it ever inspectsbase64d[:or invokes1] == b"." 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 is not encryption.
djangobase64-encodes plain JSON through.core .signing .dumps JSONSerializer. Never place secrets, API keys, or PII inside a signed cookie assuming the client cannot read it. - Letting
SECRET_KEY_FALLBACKSgrow unboundedly amplifies CPU cost on forged traffic. Every invalid token hashes against every fallback key (5.92xslower at five fallbacks in our benchmark); retire expired keys promptly once your session or token"max_age"has passed. - Where
SECRET_KEY_FALLBACKSdoes not automatically apply.Signer,TimestampSigner,get_cookie_signer, signed sessions, signed messages, and Django’sPasswordResetTokenGeneratorhonorSECRET_KEY_FALLBACKS. Any third-party library or custom helper that callssalted_hmac(..., secret=settingsdirectly checks only the primary key and will break on rotation unless it loops over.SECRET_KEY) SECRET_KEY_FALLBACKSitself. - Forgetting a custom
saltcollapses trust domains. Callingdjangowith the default.core .signing .dumps salt="djangoin two different views lets a signed object issued by one view pass.core .signing" djangoin the other..core .signing .loads
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.