Android Change password of encrypted Room DB with SQLCipher

1.1k Views Asked by At

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

There are 1 best solutions below

0
On BEST ANSWER

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.