Skip to main content

Detect tampered signed values

When you transmit data to a client that you expect to receive back later, you must ensure the data has not been modified. If a user changes a user ID in a cookie or a price in a hidden form field, itsdangerous detects this tampering by verifying a cryptographic signature.

The Signer class in signer.py provides the core mechanism for this protection. It appends a signature to your data using a secret key. When you attempt to retrieve the data, Signer.unsign recalculates the signature and compares it to the one provided. If even a single bit of the signed value is altered, the signatures will not match, and itsdangerous will raise a BadSignature exception.

Internally, Signer.sign concatenates your original bytes with a separator (defaulting to .) and a base64-encoded HMAC signature. The Signer.unsign method performs the inverse: it splits the string at the last separator, verifies the signature using Signer.verify_signature, and returns the original payload if valid. If verification fails, the BadSignature exception includes a payload attribute containing the tampered data, allowing you to inspect what was sent even if you reject it.

from itsdangerous import BadSignature, Signer

signer = Signer(b"secret-key")
value = b"my-data"

# Call sign exactly once
signed_value = signer.sign(value)

# Call unsign exactly twice
# 1. For the valid signed value
verified = signer.unsign(signed_value)
assert verified == value

# 2. For a tampered value inside a try block
tampered_value = signed_value[:-1] + b"!"
try:
signer.unsign(tampered_value)
except BadSignature as e:
assert e.payload == value