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
-
InvalidKeyKey is not exactly 32 bytes.
-
InvalidTokenToken is not valid base62 or is too short to contain all fields.
-
InvalidVersionToken version byte is not 0xBA.
-
TokenExpiredToken age exceeds the TTL passed to
decrypt_with_ttl. -
DecryptionFailedAEAD decryption failed. The token was tampered with or the wrong key was used.
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.