corvix.crypto

Fernet-based token encryption helpers and SQLAlchemy encrypted column type.

Classes

EncryptedText

SQLAlchemy column type that transparently Fernet-encrypts values at rest.

Functions

get_fernet(→ cryptography.fernet.Fernet)

Return a Fernet instance keyed from the TOKEN_ENCRYPTION_KEY env var.

encrypt_token(→ str)

Encrypt a plaintext token string with Fernet symmetric encryption.

decrypt_token(→ str)

Decrypt a Fernet-encrypted token string back to plaintext.

Module Contents

corvix.crypto.get_fernet() cryptography.fernet.Fernet[source][source]

Return a Fernet instance keyed from the TOKEN_ENCRYPTION_KEY env var.

Raises:

RuntimeError: if TOKEN_ENCRYPTION_KEY (or TOKEN_ENCRYPTION_KEY_FILE) is not set.

corvix.crypto.encrypt_token(plaintext: str) str[source][source]

Encrypt a plaintext token string with Fernet symmetric encryption.

Returns:

A URL-safe base64-encoded Fernet token (starts with gAAAAA).

corvix.crypto.decrypt_token(ciphertext: str) str[source][source]

Decrypt a Fernet-encrypted token string back to plaintext.

Raises:

cryptography.fernet.InvalidToken: if the ciphertext is invalid or the key is wrong.

class corvix.crypto.EncryptedText(*args: Any, **kwargs: Any)[source][source]

Bases: sqlalchemy.types.TypeDecorator

SQLAlchemy column type that transparently Fernet-encrypts values at rest.

The database column stores a URL-safe base64 Fernet token (plain TEXT). Python code reads and writes the original plaintext string.

Requires the TOKEN_ENCRYPTION_KEY environment variable (or TOKEN_ENCRYPTION_KEY_FILE for Docker secret file support) to be set at application startup and during migrations.

impl[source][source]
cache_ok = True[source][source]

Marks this type as safe to use with SQLAlchemy’s statement cache.

process_bind_param(value: str | None, dialect: object) str | None[source][source]

Encrypt the Python value before writing it to the database.

process_result_value(value: str | None, dialect: object) str | None[source][source]

Decrypt the database value when loading it into Python.