Skip to main content

Module cipher

Module cipher 

Source
Expand description

sqlite3mc encryption configuration.

§Encryption flow

This crate uses sqlite3mc (SQLite3 Multiple Ciphers) to encrypt SQLite databases at rest. The encryption is transparent to SQL – once a database is opened and keyed, all reads and writes are automatically encrypted/decrypted by the SQLite pager layer.

The flow when opening a database is:

  1. Opensqlite3_open_v2 creates or opens the database file. At this point the file is opaque (encrypted) and no data can be read.

  2. Configure cipherPRAGMA cipher = 'chacha20' fixes the on-disk cipher before the key activates it.

  3. KeyPRAGMA key = "x'<hex>'" passes the 32-byte K_intermediate (hex-encoded) to sqlite3mc as a raw key. The x'...' syntax tells sqlite3mc to use the bytes directly as the page-encryption key, bypassing the passphrase KDF (PBKDF2-SHA256) that a plain-string key would otherwise be run through. After this point, every page read from disk is decrypted and every page written to disk is encrypted.

  4. Verify – We immediately read from sqlite_master to confirm the key is correct. If the key is wrong, sqlite3mc returns SQLITE_NOTADB because the decrypted page header won’t match the expected SQLite magic bytes. We surface this as a clear error.

  5. Configure connection – The target-specific journal mode and every connection-level invariant are set and verified.

The default cipher is ChaCha20-Poly1305 (authenticated encryption). All crypto is built into the sqlite3mc amalgamation – no OpenSSL or other external crypto library is needed on any platform.

Functions§

export_plaintext_copy
Creates a plaintext (unencrypted) copy of an already-open encrypted database.
import_plaintext_copy
Imports data from a plaintext (unencrypted) database into an already-open encrypted database.
integrity_check
Runs PRAGMA integrity_check and returns whether the database is healthy.
open_encrypted
Opens a database, applies the encryption key, and configures the connection.