Sometimes you just want to send some data to untrusted environments. But how to do this? The trick involves signing. Given a key only you know and some random data, you can cryptographically sign them and, hand it over to someone else, and when you get the data back you can easily ensure that nobody tampered with it.
Granted, the receiver can decode the contents and look into the package, but they can not modify the contents unless they also have your secret key. So if you keep the key secret and complex, you will be fine.
Internally it uses HMAC and SHA1 for signing and bases the implementation on the Django signing module. The library is BSD licensed and written by Armin Ronacher though most of the copyright for the design and implementation goes to Simon Willison and the other amazing Django people that made this library possible.
The most basic interface is the signing interface. With Signer can be used to attach a signature to a specific string:
>>> from itsdangerous import Signer
>>> s = Signer('secret-key')
>>> s.sign('my string')
'my string.wh6tMHxLgJqB6oY1uT73iMlyrOA'
The signature is appended to the string, separated by a dot (.). To validate the string, use the unsign() method:
>>> s.unsign('my string.wh6tMHxLgJqB6oY1uT73iMlyrOA')
'my string'
If unicode strings are provided, an implicit encoding to utf-8 happens. However after unsigning you don’t be able to tell if it was unicode or a bytestring.
If the unsining fails you will get an exception:
>>> s.unsign('my string.wh6tMHxLgJqB6oY1uT73iMlyrOX')
Traceback (most recent call last):
...
itsdangerous.BadSignature: Signature "wh6tMHxLgJqB6oY1uT73iMlyrOX" does not match
If you want to expire signatures you can use the TimestampSigner which will additionally put a timestamp information in and sign this. On unsigning you can validate if the timestamp did not expire:
>>> from itsdangerous import TimestampSigner
>>> s = TimestampSigner('secret-key')
>>> string = s.sign('foo')
>>> s.unsign(string, max_age=5)
Traceback (most recent call last):
...
itsdangerous.SignatureExpired: Signature age 15 > 5 seconds
Because strings are hard to handle this module also provides a serilization interface similar to json/pickle and others. Internally it does in fact use simplejson by default which however can be changed if you subclass. The Serializer class implements that:
>>> from itsdangerous import Serializer
>>> s = Serializer('secret-key')
>>> s.dumps([1, 2, 3, 4])
'[1, 2, 3, 4].r7R9RhGgDPvvWl3iNzLuIIfELmo'
And it can of course also load:
>>> s.loads('[1, 2, 3, 4].r7R9RhGgDPvvWl3iNzLuIIfELmo')
[1, 2, 3, 4]
If you want to have the timestamp attached you can use the TimedSerializer.
Often it is helpful if you can pass these trusted strings to environments where you only have a limited set of characters available. Because of this, itsdangerous also provides URL safe serializers:
>>> from itsdangerous import URLSafeSerializer
>>> s = URLSafeSerializer('secret-key')
>>> s.dumps([1, 2, 3, 4])
'WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo'
>>> s.loads('WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo')
[1, 2, 3, 4]
All classes also accept a salt argument. The name might me misleading because usually if you think of salts in cryptography you would expect the salt to be something that is stored alongside the resulting signed string as a way to prevent rainbow table lookups. Such salts are usually public.
In “itsdangerous” like in the original Django implementation, the salt serves a different purpose. You could describe it as namespacing. It’s still not critical if you disclose it because without the secret key it does not help an attacker.
Let’s assume that you have to links you want to sign. You have the activation link on your system which can activate a user account and then you have an upgrade link that can upgrade a user’s account to a paid account which you send out via email. If in both cases all you sign is the user ID a user could reuse the variable part in the URL from the activation link to upgrade the account. Now you could either put more information in there which you sign (like the intention: upgrade or activate), but you could also use different salts:
>>> s1 = URLSafeSerializer('secret-key', salt='activate-salt')
>>> s1.dumps(42)
'NDI.kubVFOOugP5PAIfEqLJbXQbfTxs'
>>> s2 = URLSafeSerializer('secret-key', salt='upgrade-salt')
>>> s2.dumps(42)
'NDI.7lx-N1P-z2veJ7nT1_2bnTkjGTE'
>>> s2.loads(s1.dumps(42))
Traceback (most recent call last):
...
itsdangerous.BadSignature: Signature "kubVFOOugP5PAIfEqLJbXQbfTxs" does not match
Only the serializer with the same salt can load the value:
>>> s2.loads(s2.dumps(42))
42
This class can sign a string and unsign it and validate the signature provided.
Salt can be used to namespace the hash, so that a signed string is only valid for a given namespace. Leaving this at the default value or re-using a salt value across different parts of your application where the same signed value in one part can mean something different in another part is a security risk.
See The Salt for an example of what the salt is doing and how you can utilize it.
Returns the signature for the given value
Signs the given string.
Unsigns the given string.
Just validates the given signed value. Returns True if the signature exists and is valid, False otherwise.
Works like the regular Signer but also records the time of the signing and can be used to expire signatures. The unsign method can rause a SignatureExpired method if the unsigning failed because the signature is expired. This exception is a subclass of BadSignature.
Returns the current timestamp. This implementation returns the seconds since 1/1/2011. The function must return an integer.
Signs the given string and also attaches a time information.
Used to convert the timestamp from get_timestamp into a datetime object.
Works like the regular unsign() but can also validate the time. See the base docstring of the class for the general behavior. If return_timestamp is set to True the timestamp of the signature will be returned as naive datetime.datetime object in UTC.
Just validates the given signed value. Returns True if the signature exists and is valid, False otherwise.
This class provides a serialization interface on top of the signer. It provides a similar API to json/pickle/simplejson and other modules but is slightly differently structured internally. If you want to change the underlying implementation for parsing and loading you have to override the load_payload() and dump_payload() functions.
This implementation uses simplejson for dumping and loading.
Changed in version 0..
Dumps the encoded object into a bytestring. This implementation uses simplejson.
Returns URL-safe, sha1 signed base64 compressed JSON string.
If compress is True (the default) checks if compressing using zlib can save some space. Prepends a ‘.’ to signify compression. This is included in the signature, to protect against zip bombs.
Loads the encoded object. This implementation uses simplejson.
Reverse of dumps(), raises BadSignature if the signature validation fails.
Uses the TimestampSigner instead of the default Signer().
Reverse of dumps(), raises BadSignature if the signature validation fails. If a max_age is provided it will ensure the signature is not older than that time in seconds. In case the signature is outdated, SignatureExpired is raised which is a subclass of BadSignature. All arguments are forwarded to the signer’s unsign() method.
Works like Serializer but dumps and loads into a URL safe string consisting of the upper and lowercase character of the alphabet as well as '_', '-' and '.'.
Works like TimedSerializer but dumps and loads into a URL safe string consisting of the upper and lowercase character of the alphabet as well as '_', '-' and '.'.
This error is raised if a signature does not match
Signature timestamp is older than required max_age. This is a subclass of BadSignature so you can use the baseclass for catching the error.