---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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` (`django/core/signing.py: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`** (`django/core/signing.py:Signer`), **`TimestampSigner`** (`django/core/signing.py: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` (`django/utils/crypto.py:salted_hmac`):

```python
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`, `django/core/signing.py: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` (`django/core/signing.py: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:

```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!

```text figure=signing-rotation
Key rotation & salted signing: SECRET_KEY_FALLBACKS cost and Django 6.1 cookie salt v2

Signer.unsign() verification latency (50,000 calls x 5 trials, microseconds / call):
  Primary SECRET_KEY (1 HMAC)             6.08 us  (1.00x)
  Fallback #1 (2 HMACs)                  11.41 us  (1.88x)
  Fallback #3 (4 HMACs)                  22.39 us  (3.68x)
  Fallback #5 (6 HMACs)                  35.95 us  (5.92x)
  Invalid signature (all 6 HMACs)        34.67 us  (5.70x)

Django 6.1 cookie signer salt (length-prefixed v2 prevents collisions):
  Legacy (cookie_name + salt): ('ab', 'c') -> 'abc'  ==  ('a', 'bc') -> 'abc'
  Django 6.1 v2:               ('ab', 'c') -> 'django.http.cookies.v2:1:cab'
                               ('a', 'bc') -> 'django.http.cookies.v2:2:bca'
```

*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:

```text recording=ch05-security
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` (`django/core/signing.py:_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` (`django/core/signing.py: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 is not encryption.** `django.core.signing.dumps` (`django/core/signing.py:dumps`) base64-encodes plain JSON through `JSONSerializer` (`django/core/signing.py:JSONSerializer`). Never place secrets, API keys, or PII inside a signed cookie assuming the client cannot read it.
- **Letting `SECRET_KEY_FALLBACKS` grow unboundedly amplifies CPU cost on forged traffic.** Every invalid token hashes against every fallback key (`5.92x` slower at five fallbacks in our benchmark); retire expired keys promptly once your session or token `"max_age"` has passed.
- **Where `SECRET_KEY_FALLBACKS` does *not* automatically apply.** `Signer`, `TimestampSigner`, `get_cookie_signer`, signed sessions, signed messages, and Django's `PasswordResetTokenGenerator` honor `SECRET_KEY_FALLBACKS`. Any third-party library or custom helper that calls `salted_hmac(..., secret=settings.SECRET_KEY)` directly checks only the primary key and will break on rotation unless it loops over `SECRET_KEY_FALLBACKS` itself.
- **Forgetting a custom `salt` collapses trust domains.** Calling `django.core.signing.dumps` with the default `salt="django.core.signing"` in two different views lets a signed object issued by one view pass `django.core.signing.loads` (`django/core/signing.py:loads`) in the other.

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](csp-and-headers.md).
