Android Room database: SQLCipher 2023 update
Encrypt your Room Database, updated
A couple of years ago, I wrote how to protect your Room or SQLite Database with SQLCipher. The article has been read thousands of times and I felt like It was due for an update.
SQLCipher have evolved slightly and people like you may want to migrate to the latest version 4.5.5
. This version adds support for the latest SQLite version 3.4.2
as well a set of security and efficiency improvement. For more info, please check the changelog.
Dependencies package is changing
First of all, the team changed how to import the dependency, so you will need to head to app/build.gradle
and the dependencies section or if you use the new version catalog feature, open .toml file.
Add the dependency as follow
implementation 'net.zetetic:sqlcipher-android:4.5.5@aar'
Notice how the package name has changed moving the “android” as a suffix instead of a prefix.
Then sync your project to update the gradle dependencies.
Load the native library
You will need to load the native library binary manually with System.loadLibrary()
. SQLCipher is a C library allowing for great performance.
Depending on your configuration you may want to load the library binary in your Application class, in your Activity or even within your Dependency Injection setup.
Always make sure you load it the library binary before accessing your database.
System.loadLibrary("sqlcipher")
Update the database factory
SQLCipher introduces a new way to create the encrypted database. It replaces the old SupportFactory
with SupportOpenHelperFactory
.
SupportOpenHelperFactory(passphrase, object : SQLiteDatabaseHook {} )
The SQLiteDatabaseHook
callback also changes slightly, providing a SQLConnection
instead of a SQLDatabase
object to preKey
and postKey
functions.
override fun postKey(connection: SQLiteConnection)
override fun preKey(connection: SQLiteConnection)
To execute the SQL commands, you will need to call execute
instead of rawExecSQL
like so:
connection.execute("PRAGMA cipher_memory_security = OFF", null, null)
You can find the full diff
here on github.
Note: there might be other steps to follow depending your configuration.
Thanks for reading, I hope it will be usefull to you, if that’s the case please clap 👏