SQLCipher on Android (keys, KDF cost, rekeying safely)
androidsqlcipherencryptionroomkeystoreperformance
SQLCipher encrypts a SQLite database with AES. The Message app uses sqlcipher-android under Room, with a random 256-bit key wrapped by the Android Keystore and no silent fallback to an unencrypted database (it crashes instead). Two hard-won lessons: how you hand over the key decides startup speed, and changing how the key is applied can brick every installed copy.
Passphrase vs raw key
- Passing the key as a passphrase makes SQLCipher run PBKDF2-HMAC-SHA512 with 256,000 iterations on every connection open, and Room's WAL connection pool opens several. That was a visible part of a multi-second cold start.
- Passing it as a raw key, the literal string
x'<64 hex chars>', skips the KDF. When the key is already random 256-bit material, the KDF adds nothing. - Switching an existing file from passphrase to a plain raw key requires a rekey, unless you use the raw-key-with-salt form described below, which opens the existing file as is.
The rekey that crashed every phone (v2.32.0)
The conversion used ATTACH ... KEY "x'...'" and SELECT sqlcipher_export('staging'). sqlcipher_export does not copy PRAGMA user_version. The new file had the full schema and all rows but version 0, so Room ran onCreate instead of onUpgrade and failed schema validation: crash on every launch, data intact. Rollback on the server could not help installed phones, because Android refuses a versionCode downgrade and the old code could not open a raw-keyed file anyway. The fix release (v2.32.1) added a shim that opens raw-keyed files and, once, restores user_version by inferring it from schema markers (newest column or table present), leaving unrecognizable files alone so Room fails loudly rather than losing data.
The release's device test had passed because it created and reopened the database at the same schema version. Any rekey or export test must start from a fixture at the previous schema version and open through Room at the new one.
Skipping the KDF without touching the file (v2.34.0)
The safer re-land did not convert the database at all. SQLCipher also accepts the result of its key derivation directly, as a raw key with an explicit salt: x'<64 hex key><32 hex salt>' (99 ASCII bytes). Given the passphrase and the salt stored in the first 16 bytes of the database file, PBKDF2-HMAC-SHA512 with SQLCipher 4's defaults (256,000 iterations, 32-byte key) produces exactly the key SQLCipher would derive, and the same unmodified file opens with no KDF.
- Derive once, on a low-priority background thread, after the launch that discovers there is no stored spec. That launch still uses the passphrase, so it is never slower than before.
- Keep the spec only if a probe open with it succeeds, then store it wrapped by the Keystore exactly like the passphrase (it opens the same file, so it is equally sensitive).
- On later launches: read the salt from the file, check the stored spec's salt suffix matches, probe-open once (cheap, no KDF), then hand it to Room. If it ever stops opening the file, clear it and re-derive; the passphrase is never touched.
- Nothing is written to the database: no rekey, no export, no rename. The worst case is the old passphrase path.
- Hand-roll PBKDF2 over raw bytes (a short HMAC loop). The JCE's PBKDF2WithHmacSHA512 takes a char[] and UTF-8-encodes it, which cannot represent a random 32-byte passphrase. Test it against an RFC vector and cross-check with the JCE on ASCII input.
- Measured: about 270 to 515 ms to derive once on the emulator; every later connection skips it.
This is the general pattern when a cost is paid per open: cache the expensive derived value (protected as strongly as the original secret) instead of migrating stored data.
A safe rekey design (if you must convert)
- Out of place: export into
<db>.rekey-staging, setPRAGMA staging.user_versionto the source's value, verify staging opens with the new key, delete the original's-wal/-shm/-journal(after closing the source, which checkpoints), then atomic rename. - Rejected: in-place
PRAGMA rekey. A process kill mid-rewrite (and process start is exactly when OEM task killers strike) leaves a file neither key opens. - Decision table: flag says raw, use raw; no file, create raw; raw opens, set flag; passphrase opens, rekey then verify then set flag; rekey throws, stay on passphrase and retry next launch; never delete or recreate the original.
- Pass a log-only
DatabaseErrorHandlerto every probe open. The library's default handler deletes the file on "corruption", and a wrong-key probe can look like corruption.
API gotchas (sqlcipher-android 4.6.1)
rawExecSQLsilently does nothing forATTACHand export: no error, the attached DB never shows inPRAGMA database_list, staging stays 0 bytes. UseexecSQLfor statements andrawQueryforSELECT sqlcipher_export(...).ATTACHneeds the main connection opened withCREATE_IF_NECESSARY, because the attached file inherits main's flags and does not exist yet.- Uninstalling the app destroys its Keystore wrapping key, so a copied database file cannot be pushed back after an uninstall. Rebuild test states from scratch instead.
- A lazy open helper factory moves open failures into whichever coroutine first touches the database; process-lifetime collectors need a
CoroutineExceptionHandler, or Robolectric tests (no AndroidKeyStore) fail with uncaughtKeyStoreException.