Skip to content

Commit

Permalink
Add cipher PRAGMA api for adopting sqlcipher lib
Browse files Browse the repository at this point in the history
  • Loading branch information
qhhonx committed Jul 8, 2019
1 parent e5030ab commit c254881
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ data class DatabaseConfiguration(
val busyTimeout: Int = 2500,
val pageSize: Int? = null,
val inMemory: Boolean = false,
val basePath: String? = null
val basePath: String? = null,
val key: String? = null,
val rekey: String? = null
) {
init {
checkFilename(name)
Expand All @@ -53,4 +55,4 @@ enum class JournalMode {
DELETE
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,26 @@ fun DatabaseConnection.stringForQuery(sql:String):String = withStatement(sql){
stringForQuery()
}

/**
* Sets the database cipher key.
*
* @param cipherKey the database cipher key
*/
fun DatabaseConnection.setCipherKey(cipherKey: String) {
withStatement("PRAGMA key = \"$cipherKey\";") { execute() }
}

/**
* Resets the database cipher key.
*
* @param oldKey the old database cipher key
* @param newKey the new database cipher key
*/
fun DatabaseConnection.resetCipherKey(oldKey: String, newKey: String) {
setCipherKey(oldKey)
withStatement("PRAGMA rekey = \"$newKey\";") { execute() }
}

/**
* Gets the database version.
*
Expand Down Expand Up @@ -84,4 +104,4 @@ fun DatabaseConnection.updateJournalMode(value: JournalMode):JournalMode{
fun DatabaseConnection.updateForeignKeyConstraints(enabled: Boolean){
val newValue = if(enabled){1}else{0}
withStatement("PRAGMA foreign_keys=$newValue") { execute() }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,25 @@ class NativeDatabaseManager(private val path:String,
val conn = NativeDatabaseConnection(this, nativeOpen(
path,
CREATE_IF_NECESSARY,
"asdf",
"sqliter",
false,
false,
-1,
-1,
configuration.busyTimeout
))

if (configuration.rekey == null) {
configuration.key?.let { conn.setCipherKey(it) }
} else {
if (configuration.key == null) {
// If executed here, it indicate that setCipherKey to `rekey` due to the old key is not set yet.
conn.setCipherKey(configuration.rekey)
} else {
conn.resetCipherKey(configuration.key, configuration.rekey)
}
}

if(configuration.foreignKeyConstraints){
conn.updateForeignKeyConstraints(true)
}
Expand Down Expand Up @@ -91,4 +102,4 @@ class NativeDatabaseManager(private val path:String,
@SymbolName("SQLiter_SQLiteConnection_nativeOpen")
private external fun nativeOpen(path:String, openFlags:Int, label:String,
enableTrace:Boolean, enableProfile:Boolean,
lookasideSlotSize:Int, lookasideSlotCount:Int, busyTimeout:Int):Long
lookasideSlotSize:Int, lookasideSlotCount:Int, busyTimeout:Int):Long

0 comments on commit c254881

Please sign in to comment.