-
-
Save shafty023/f8ed96e120fd5312c136eba251004fe4 to your computer and use it in GitHub Desktop.
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 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.
@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
@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.
How to secure this passcode in android code.