Detect tampered signed values
When you transmit data to a client and expect it back later, you must ensure the data has not been modified. If a user changes a value in a cookie or a URL parameter, itsdangerous detects this tampering by verifying a cryptographic signature.
The Signer class in itsdangerous provides the core mechanism for this protection. It appends a signature to your data using a secret key. When the data returns, Signer.unsign verifies that the signature matches the payload. If even a single bit of the signed value is altered, the verification fails.
To protect your data, initialize a Signer with a secret key. Use the sign method to create a signed string and unsign to retrieve the original value. If the signature is invalid, unsign raises a BadSignature exception. This exception includes a payload attribute, which contains the data that failed the check, allowing for inspection if necessary.
from itsdangerous import BadSignature, Signer
signer = Signer(b"secret-key")
signed_value = signer.sign(b"user-id-123")
unsigned_data = signer.unsign(signed_value)
assert unsigned_data == b"user-id-123"
tampered_value = b"v" + signed_value[1:]
try:
signer.unsign(tampered_value)
except BadSignature as e:
assert e.payload == b"vser-id-123"
Internally, Signer.unsign splits the input string using the defined separator (defaulting to .). It then uses Signer.verify_signature to compare the provided signature against a newly generated signature of the payload using the secret_key. The comparison is performed using a constant-time string comparison to prevent timing attacks. If verify_signature returns False, unsign raises the BadSignature error.