Encrypting data in Android Room DB
Learn how to encrypt/decrypt DB data by writing a layer on top of Room Dao’s
Android Room library is great and very easy to use but it doesn’t provide any feature to encrypt/decrypt data(as of 2021). So in this post I will be sharing a way that I have used in many of my projects to do this by adding a code layer before calling Room Dao methods. For this post it is a pre-requisite that you understand Room Library and have implemented it in one of your apps.
In a nutshell this is what we are going to do:
From our code (basically Repository) we are not going to call Dao method directly. we will make a new class SecureDao. This class will be responsible to encrypt/decrypt data using some class (like CryptoUtils) and call dao methods internally.
Let’s implement it for a very basic use case. Suppose that you want to insert userId into a user table with two columns only : key, userId.
For this we will have a very basic below Dao method in UserDataDao interface:
@Insert(onConflict = OnConflictStrategy.ABORT)
suspend fun insertUserId(userData: UserData)
Now we will make same method in our UserDataDaoSecure class, In the constructor we will have userDataDao and cryptoUtils:
suspend fun insertLoginData(userDataEntity: UserDataEntity) {
userDataDao.insertUserId(encrypt(userDataEntity))
}private fun encrypt(userDataEntity: UserDataEntity):UserDataEntity{
userDataEntity.let{
return UserDataEntity(
it.key, // no operation on this
cryptoUtils.encrypt(it.userId) // encrypt it
)
}
}
Now from your code or repository layer, you can simply call userDataDaoSecure.insertLoginData(userDataEntity)
This is the simple trick that I use to encrypt/decrypt data in Android DB. To improve it further I usually implement Dao interface in my secure Dao class. This ensures that whatever methods I have in my dao, I have to implement them in my secureDao class.
This was a very simple example. To see it’s usage and the code in securityUtils you can check this project in github:
Safe-Box is an open source android app. You are welcome to contribute to this project or raise any issue. You can also download it from play store