Change encryption key on Android?

Hello, how to do the reencryption of Realm on Android properly?

Use case:
User opens app (calls onCreate) -> user enters password (key for realm encryption) (calls installEncryptedRealm) -> user changes password (calls reencryptRealm)

I was unable to find solution for this use case elsewhere. My solution seems to work, but I don’t like that I have to store filename in SharedPreferences (if i don’t, Realm uses again default.realm after restart).

class Diary : Application() {

    override fun onCreate() {
        super.onCreate()
        Realm.init(this)
        Realm.removeDefaultConfiguration()
    }

    fun installEncryptedRealm(key: ByteArray) {
        // HACK: store realm filename in shared prefs.. realm somehow can't remember it
        val realmFileName = getSharedPreferences("user_prefs", Context.MODE_PRIVATE).getString("realm_file", null) ?: "diary.realm"
        Realm.setDefaultConfiguration(buildRealmConfiguration(key, realmFileName))
    }

    fun reencryptRealm(newKey: ByteArray) {
        val newName = System.currentTimeMillis().toString() + ".realm"
        val newFile = File(applicationContext.filesDir, newName)
        // HACK to remember realm filename
        getSharedPreferences("user_prefs", Context.MODE_PRIVATE).edit().putString("realm_file", newName).apply()
        val realm = Realm.getInstance(Realm.getDefaultConfiguration())
        realm.writeEncryptedCopyTo(newFile, newKey)
        realm.close()
        Realm.deleteRealm(Realm.getDefaultConfiguration())
        Realm.removeDefaultConfiguration()
        Realm.setDefaultConfiguration(buildRealmConfiguration(newKey, newName))
    }

    private fun buildRealmConfiguration(key: ByteArray, name: String): RealmConfiguration {
        return RealmConfiguration.Builder()
            .name(name)
            .encryptionKey(key)
            .schemaVersion(REALM_MIGRATION_VERSION)
            .migration(MyRealmMigration())
            .build()
    }
}

Code: https://github.com/SirionRazzer/Diary/commit/96289f70b5b5755caacc7312dc863e0a25973660