Skip to content

Instantly share code, notes, and snippets.

@shafty023
Created June 9, 2020 23:19
Show Gist options
  • Save shafty023/f8ed96e120fd5312c136eba251004fe4 to your computer and use it in GitHub Desktop.
Save shafty023/f8ed96e120fd5312c136eba251004fe4 to your computer and use it in GitHub Desktop.
Encrypted Room db
abstract class EncryptedDatabase : RoomDatabase() {
companion object {
fun getInstance(passcode: CharArray, context: Context):
EncryptedDatabase = buildDatabase(passcode, context)
private fun buildDatabase(
passcode: CharArray,
context: Context
): EncryptedDatabase {
// DatabaseKeyMgr is a singleton that all of the above code is wrapped into.
// Ideally this should be injected through DI but to simplify the sample code
// we'll retrieve it as follows
val dbKey = DatabaseKeyMgr.getInstance().getCharKey(passcode, context)
val supportFactory = SupportFactory(SQLiteDatabase.getBytes(dbKey))
return Room.databaseBuilder(context, EncryptedDatabase::class.java,
"encrypted-db").openHelperFactory(supportFactory).build()
}
}
}
@shafty023
Copy link
Author

@RahulSDeshpande sorry for the extremely late response, just now seeing this. DatabaseKeyMgr is a class you'd create that encapsulates all of the functions/logic I mention in my guide. That way you have a centralized place to create/store/retrieve the database key.

SupportFactory comes from the url you mentioned.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment