Skip to content

Instantly share code, notes, and snippets.

@shafty023
Created June 9, 2020 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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()
}
}
}
@yaminijain
Copy link

How to secure this passcode in android code.

@shafty023
Copy link
Author

@yaminijain You should never store the passcode, or unencrypted db key in Android code or in any type of persistent storage. Once you use it here to unlock the database you should zero out the CharArray so that someone can't use a tool like Frida (https://frida.re/) to dump your app's running memory and find the passcode hiding. So never never store any unencrypted passcode. The only thing you can store is the encrypted db passcode and then use the user passcode to decrypt it.

@RahulSDeshpande
Copy link

RahulSDeshpande commented Aug 31, 2023

@shafty023
Can you please explain what are the following classes?

  • DatabaseKeyMgr
  • SupportFactory

From which lib did you get these classes?

Are these from the this lib?
https://github.com/sqlcipher/android-database-sqlcipher

@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