How to Encrypt Existing Android Room DB

Currently, creating a Room database looks like so:

            return Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, DB_NAME)
                .addMigrations(...)
                .fallbackToDestructiveMigrationFrom(...)
                .build()

I want to encrypt this DB, so using SQLCipher, I’ve generated a secure passphrase, and can create a new, encrypted DB like so:

        val factory = SupportFactory(passphrase, null, false)
        return Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, DB_NAME)
                .openHelperFactory(factory)
                .addMigrations(...)
                .fallbackToDestructiveMigrationFrom(...)
                .build()

This all works fine, but it only creates a new, encrypted DB, which forces me to delete the old DB before creating the new one in this fashion. How do I go about encrypting an existing DB?
I’ve looked at the example #1 that some people have recommended, but that doesn’t really help, since it’s just a command line instruction to encrypt/attach a DB. Is there not a way to do this through the gradle library?

My ultimate goal is to encrypt the existing DB such that it retains the data.

FWIW, that was discussed previously in this board — see this post, for example.

Ah, good find @commonsguy. This is exactly what I ended up doing. I was so surprised that development for your SafeRoom library ended, as the new SQLCipher library doesn’t have any of the convenient util methods you provided.
Have you thought about forking the new repo and making a PR to include your utils class?
Either way, I’ll be writing a (free) Medium article about this solution to make it easier for other devs to find this information, instead of scouring these forums for an answer.

By the way, I found that the method you linked requires the WRITE_EXTERNAL_STORAGE permission. One way to go around this was to change the creation of the tmp file like so:

val newFile = File.createTempFile("sqlcipherutils", "tmp", File(originalFile.parent))

In any case, thanks for providing a solution to this! SafeRoom has been a lifesaver.

If the Zetetic team would like that contribution, I’d be happy to make it! I forget if we discussed it back when I made the original contributions or not.

Off the cuff, I don’t see how. I use getCacheDir(), which is on internal storage.

That would be awesome.

Sorry, I should have clarified: This issue only stems in a test environment (such as JUnit). I haven’t dug into any workarounds or resolutions, as this code change addresses the issue and doesn’t really have any other side-effects since the tmp file is deleted either way.

This could also be a permission requirement for API 23 and above.