我们有这样的数据库 module
:
val dataBaseModule= module {
single { AppDataBase.getInstance(androidContext()) }
}
现在我们想像这样加密我们的数据库SQLiteDatabase
:
val passphrase: ByteArray = SQLiteDatabase.getBytes("123".toCharArray())
val factory = SupportFactory(passphrase)
并设置factory
如下:
Room.databaseBuilder(context, AppDataBase::class.java, "X")
.openHelperFactory(factory)
.build()
那么我们就不会password
像static
我们"123"
想要从用户动态中获取它一样。
像这样的东西:
abstract class AppDataBase : RoomDatabase() {
companion object {
private val instance: AppDataBase? = null
fun getInstance(context: Context,pass: String): AppDataBase = instance ?: synchronized(this) {
buildDataBase(context,pass) as AppDataBase
}
private fun buildDataBase(context: Context,pass:String): RoomDatabase {
val passphrase: ByteArray = SQLiteDatabase.getBytes(pass.toCharArray())
val factory = SupportFactory(passphrase)
return Room.databaseBuilder(context, AppDataBase::class.java, "X")
.openHelperFactory(factory)
.build()
}
}
}
注意:考虑到我们使用Koin
它并在编译时创建实例,这怎么可能?