Branca Tokens for Python
Authenticated and encrypted API tokens using modern crypto.
What?
Branca is a secure easy to use token format which makes it hard to shoot yourself in the foot. It uses IETF XChaCha20-Poly1305 AEAD symmetric encryption to create encrypted and tamperproof tokens. Payload itself is an arbitrary sequence of bytes. You can use for example a JSON object, plain text string or even binary data serialized by MessagePack or Protocol Buffers.
Although not a design goal, it is possible to use Branca as an alternative to JWT.
Install
Install the library using pip. Note that you also must have libsodium installed.
$ brew install libsodium
$ pip install pybranca
Usage
The payload of the token can be anything, like a simple string.
import secrets
from branca import Branca
key = secrets.token_bytes(32)
branca = Branca(key)
token = branca.encode("Hello world!")
payload = branca.decode(token)
print(token)
print(payload)
For more complicated data structures JSON is an usual choice.
import json
import secrets
from branca import Branca
key = secrets.token_bytes(32)
branca = Branca(key)
string = json.dumps({"scope" : ["read", "write", "delete"]})
token = branca.encode(string)
payload = branca.decode(token)
print(token)
print(payload)
print(json.loads(payload))
By using MessagePack you can have more compact tokens.
import msgpack
from branca import Branca
key = secrets.token_bytes(32)
branca = Branca(key)
packed = msgpack.dumps({"scope" : ["read", "write", "delete"]})
token = branca.encode(packed)
payload = branca.decode(token)
print(token)
print(payload)
print(msgpack.loads(payload, raw=False))
License
The MIT License (MIT). Please see License File for more information.