Branca v0.2.0 Branca View Source
Branca allows you to generate and verify encrypted API tokens (IETF XChaCha20-Poly1305 AEAD). Branca specification defines the external format and encryption scheme of the token to help interoperability between userland implementations. Branca is closely based on Fernet.
Payload in Branca token is an arbitrary sequence of bytes. This means payload can be for example a JSON object, plain text string or even binary data serialized by MessagePack or Protocol Buffers.
This library expects you the set the 32 byte secret key in config/config.exs
:
config :branca, key: "supersecretkeyyoushouldnotcommit"
Link to this section Summary
Functions
Decrypts and verifies the token returning the payload on success
Decrypts and verifies the token returning the payload on success, raises an exception on error
Returns base62 encoded encrypted token with given payload
Returns base62 encoded encrypted token with given payload, raises an exception on error
Link to this section Functions
Decrypts and verifies the token returning the payload on success.
iex> token = Branca.encode("Hello world!");
iex> Branca.decode(token)
{:ok, "Hello world!"}
Optionally you can make sure tokens are valid only ttl
seconds.
iex> token = Branca.encode("Hello world!", timestamp: 123206400);
iex> Branca.decode(token)
{:ok, "Hello world!"}
iex> Branca.decode(token, ttl: 60)
{:error, :expired}
Decrypts and verifies the token returning the payload on success, raises an exception on error.
iex> token = Branca.encode("Hello world!");
iex> Branca.decode!(token)
"Hello world!"
Returns base62 encoded encrypted token with given payload.
By default token will use current timestamp and generated random nonce. This is what you almost always want to use.
iex> token = Branca.encode("Hello world!")
{:ok, "875GH233T7IYrxtgXxlQBYiFobZMQdHAT51vChKsAIYCFxZtL1evV54vYqLyZtQ0ekPHt8kJHQp0a"}
Optionally you can pass timestamp
and nonce
. You could for example opt-out
from sending timestamp
by setting it to 0
. Clock skew can be adjusted by setting
the timestamp few seconds to future.
iex> token = Branca.encode("Hello world!", timestamp: 123206400)
{:ok, "875GH233T7IYrxtgXxlQBYiFobZMQdHAT51vChKsAIYCFxZtL1evV54vYqLyZtQ0ekPHt8kJHQp0a"}
Explicit nonce
is mostly used for unit testing. If you generate nonce
yourself
make sure not to reuse the it between tokens.
iex> nonce = Salty.Random.buf(24)
iex> token = Branca.encode("Hello world!", timestamp: 123206400, nonce: nonce)
{:ok, "87x85fNayA1e3Zd0mv0nJao0QE3oNUGTuj9gVdEcrX4RKMQ7a9VGziHec52jgMWYobXwsc4mrRM0A"}
Returns base62 encoded encrypted token with given payload, raises an exception on error.
iex> token = Branca.encode("Hello world!")
"875GH233T7IYrxtgXxlQBYiFobZMQdHAT51vChKsAIYCFxZtL1evV54vYqLyZtQ0ekPHt8kJHQp0a"