Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,18 @@ class WebDatabaseHolder(private val key: String? = null) : SqlDelightDbHolder {
override val noteQueries: NoteQueries = noteDb.noteQueries

/**
* Sets the encryption key on the database connection.
* Configures SQLCipher v4 compatibility and sets the encryption key.
* Must be called BEFORE any other SQL operations (including createSchema).
* This sends PRAGMA key as the first statement to the worker.
*
* Uses `cipher=sqlcipher` with `legacy=4` to match the Desktop JVM and Android
* encryption format, enabling cross-platform encrypted backup portability.
*/
suspend fun applyKey() {
if (!key.isNullOrEmpty()) {
val escapedKey = key.replace("'", "''")
logger.d { "Setting encryption key on database" }
logger.d { "Configuring SQLCipher v4 and setting encryption key" }
driver.execute(null, "PRAGMA cipher = 'sqlcipher'", 0, null).await()
driver.execute(null, "PRAGMA legacy = 4", 0, null).await()
driver.execute(null, "PRAGMA key = '$escapedKey'", 0, null).await()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ class WebSafeRepo(private val coroutineDispatchers: CoroutineDispatchers) : Safe
logger.d { "Encrypting database" }
val holder = dbHolder ?: buildDbIfNeed()
val escapedKey = newPass.toString().replace("'", "''")
// On an unencrypted database, PRAGMA rekey encrypts it in-place
holder.driver.execute(null, "PRAGMA cipher = 'sqlcipher'", 0, null).await()
holder.driver.execute(null, "PRAGMA legacy = 4", 0, null).await()
holder.driver.execute(null, "PRAGMA rekey = '$escapedKey'", 0, null).await()
logger.d { "PRAGMA rekey executed, closing and reopening with key" }
closeDatabase()
Expand Down
Loading