Search code examples
android-roomsqlciphersqlcipher-android

Android Change password of encrypted Room DB with SQLCipher


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?


Solution

  • 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.