amaro/branca

Encrypt and decrypt Branca tokens.

Branca tokens use XChaCha20-Poly1305 authenticated encryption. Tokens are base62-encoded and URL-safe.

Example

let key = branca.generate_key()
let token = branca.encrypt(key, plaintext: <<"hello":utf8>>)
let assert Ok(plaintext) = branca.decrypt(key, token:)

Types

Errors that can occur during key parsing or token operations.

pub type Error {
  InvalidKey
  InvalidToken
  InvalidVersion
  TokenExpired
  DecryptionFailed
}

Constructors

  • InvalidKey

    Key is not exactly 32 bytes.

  • InvalidToken

    Token is not valid base62 or is too short to contain all fields.

  • InvalidVersion

    Token version byte is not 0xBA.

  • TokenExpired

    Token age exceeds the TTL passed to decrypt_with_ttl.

  • DecryptionFailed

    AEAD decryption failed. The token was tampered with or the wrong key was used.

A 256-bit key for XChaCha20-Poly1305 authenticated encryption. Generate one with generate_key or wrap existing bytes with key_from_bytes.

pub opaque type Key

Values

pub fn decrypt(
  key: Key,
  token token: String,
) -> Result(BitArray, Error)

Decrypt a Branca token and return the original plaintext. No expiry check is performed.

pub fn decrypt_with_ttl(
  key: Key,
  token token: String,
  ttl ttl: duration.Duration,
) -> Result(BitArray, Error)

Decrypt a Branca token, rejecting it if its age exceeds ttl. Age is measured as the difference between the current system time and the timestamp embedded in the token.

pub fn encrypt(key: Key, plaintext plaintext: BitArray) -> String

Encrypt plaintext into a Branca token string. The current system time is recorded in the token and a random nonce is generated for each call.

pub fn generate_key() -> Key

Generate a random Branca key using a cryptographically secure RNG.

pub fn key_from_bytes(
  bytes bytes: BitArray,
) -> Result(Key, Error)

Wrap raw bytes as a Branca key. The input must be exactly 32 bytes.

pub fn key_to_bytes(key: Key) -> BitArray

Return the raw 32 bytes of the key.

Search Document