amaro/fernet
Encrypt and decrypt Fernet tokens.
Fernet tokens are authenticated and encrypted using AES-128-CBC and HMAC-SHA256. Tokens are base64url-encoded and safe for use in URLs, headers, and cookies.
Example
let key = fernet.generate_key()
let token = fernet.encrypt(key, plaintext: <<"hello":utf8>>)
let assert Ok(plaintext) = fernet.decrypt(key, token:)
Types
Errors that can occur during key parsing or token operations.
pub type Error {
InvalidKey
InvalidToken
InvalidVersion
InvalidSignature
TokenExpired
DecryptionFailed
}
Constructors
-
InvalidKeyKey is not 32 bytes or not valid base64url.
-
InvalidTokenToken is not valid base64url or is too short to contain all fields.
-
InvalidVersionToken version byte is not 0x80.
-
InvalidSignatureHMAC verification failed. The token was tampered with or the wrong key was used.
-
TokenExpiredToken age exceeds the TTL passed to
decrypt_with_ttl. -
DecryptionFailedAES-CBC decryption or PKCS#7 unpadding failed.
Values
pub fn decrypt(
key: Key,
token token: String,
) -> Result(BitArray, Error)
Decrypt a Fernet token and return the original plaintext. The token’s HMAC is verified before decryption. No expiry check is performed.
pub fn decrypt_with_ttl(
key: Key,
token token: String,
ttl ttl: duration.Duration,
) -> Result(BitArray, Error)
Decrypt a Fernet 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 Fernet token string. The current system time is recorded in the token and a random IV is generated for each call.
pub fn generate_key() -> Key
Generate a random Fernet key using a cryptographically secure RNG.
pub fn key_from_string(
encoded encoded: String,
) -> Result(Key, Error)
Decode a key from a base64url-encoded string. Returns InvalidKey if the
string is not valid base64url or does not decode to exactly 32 bytes.
pub fn key_to_string(key: Key) -> String
Encode a key as a base64url string with padding.