2

I successfully encrypted my Room DB with SQLCipher.

I now like to give the user to option to change the DB password. So how can I change the SQLCipher password with Room DB?

1 Answer 1

2

Found the answer:

database.query("PRAGMA rekey = '$newPassword';", emptyArray())

As complete code example with context:

    fun changePassword(previousPassword: String, newPassword: String) {
        val passphrase = SQLiteDatabase.getBytes(previousPassword.toCharArray())
        val factory = SupportFactory(passphrase)

        val database = Room.databaseBuilder(applicationContext, <your_database_class>::class.java, "<database_name>")
            .openHelperFactory(factory)
            .build()

        database.query("PRAGMA rekey = '$newPassword';", emptyArray())
    }

There's even no need to close and re-open the database.

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, @dankito, your approach is interesting but in the same time is quite dangerous. Why? I made some experiments. I encrypted my SQLite database file with DB Browser for SQLite, it provides SQLCipher 4 possibilities. After that, I put the encrypted database file in assets/database folder of my Android project and implemented your solution. BUT. I got: "java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time."
This post discuss.zetetic.net/t/pragma-rekey-performance/4049 informs that "... rekey operations are expected to be fairly time consuming ...". That's why, in my opinion, rekey operation is not good choice for Android app.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.