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. Detect and encrypt or unlock – A read from sqlite_master succeeds for a plaintext (or new) database. Such a database is moved out of WAL mode and atomically encrypted with PRAGMA rekey. Existing databases with a fully encrypted header are unlocked using their old settings and migrated in place. Both key and rekey receive the 32-byte K_intermediate as a raw hex key, bypassing the passphrase KDF.

  4. Verify – We read from sqlite_master after rekeying or keying. A wrong key returns SQLITE_NOTADB because the decrypted page header does not match the expected SQLite magic bytes.

  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.

The first 32 bytes of every database header remain plaintext. This gives all targets one on-disk format and lets iOS recognize shared-container databases in WAL mode. Existing databases with fully encrypted headers are migrated in place on their first successful open.

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 writable database, applies the encryption key, and configures the connection.