Skip to content

Encryption

David Ciulla edited this page Nov 7, 2026 · 1 revision

Encryption

Laravex provides a simple, opinionated encryption API via Laravex.Encryption.Crypt. All values are encrypted using AES-256-GCM (authenticated encryption with associated data) keyed from your application's APP_KEY.

Configuration

Set APP_KEY in your .env file. Generate one with Artisan:

./artisan key:generate

The key must be a Base64-encoded 32-byte (256-bit) string prefixed with base64::

APP_KEY=base64:your-32-byte-base64-encoded-key-here=

The key is read from config/app.exs (app.key) or falls back to the APP_KEY environment variable. Crypt derives the 32-byte binary via Base.decode64/1; if the decoded value is shorter than 32 bytes, it falls back to SHA-256 of the raw key string.

Warning: If APP_KEY is not set, Laravex logs a warning to stderr and uses a development-only placeholder key. Never deploy without a properly generated key.

Encrypting Values

cipher = Laravex.Encryption.Crypt.encrypt("sensitive string")
# => "base64-encoded ciphertext"

encrypt/1 accepts a binary value and returns a Base64-encoded string containing a prepended 12-byte IV, 16-byte GCM authentication tag, and the ciphertext.

Decrypting Values

plain = Laravex.Encryption.Crypt.decrypt(cipher)
# => "sensitive string"

decrypt/1 raises if the payload is malformed or the GCM tag does not match (i.e., tampered or wrong key).

How It Works

The algorithm is Erlang's :crypto.crypto_one_time_aead/7 with :aes_256_gcm:

Step Detail
IV 12 random bytes from :crypto.strong_rand_bytes/1
Tag 16-byte GCM authentication tag
Serialization Base.encode64(iv <> tag <> cipher)

Because the full AEAD primitive is used, decryption will fail (and raise) if the ciphertext is modified in any way. You cannot swap IVs or truncate tags.

Cookie Encryption

The EncryptCookies middleware encrypts outbound Set-Cookie values and decrypts inbound cookies when session.encrypt is true in config/session.exs:

# config/session.exs
%{
  "encrypt" => true,
  ...
}

The same Crypt module is used. Cookie values that already look like a Base64 AES-GCM payload (> 40 bytes, valid Base64) are left as-is to avoid double-encryption.

Session ID Encryption

When session.encrypt is enabled, the session cookie itself (containing the session ID) is also passed through Crypt.encrypt/1 before being written to the response. This is handled transparently in Laravex.Http.Kernel.

See Also

  • Hashing — One-way PBKDF2 password hashing (use this for passwords, not Crypt)
  • Authentication — Session guard and remember-me cookies

Clone this wiki locally