Modern Apps git

← Modern-Apps.git

passwords: encrypt database and store key in secure element (access with biometrics)

Commit
4fcd138ebd634216cb38db42ccf97b6c8b815fb3
Author
Vayun Mathur <[email protected]>
When
2026-04-16 19:18 UTC (7 months ago)
Parents
8fd2056

Diff

gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex f74a4cfdba..62d8b93300 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -37,7 +37,8 @@ kotlinxSerializationJson = "1.10.0" kotlinxDatetime = "0.7.1" room = "2.8.4" -# Specialized Features (PDF, Maps, Health, Crypto)+# Special Features (PDF, Maps, Health, Crypto)+biometric = "1.2.0-alpha05" pdfViewer = "1.0.0-alpha16" glance = "1.1.1" connectClient = "1.2.0-alpha03"@@ -50,11 +51,13 @@ maplibre = "0.12.1" [libraries] # AndroidX Core & Lifecycle androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }+androidx-fragment-ktx = { group = "androidx.fragment", name = "fragment-ktx", version = "1.8.6" } androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" } androidx-lifecycle-viewmodel-ktx = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-ktx", version.ref = "lifecycle" } androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" } androidx-work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version.ref = "workRuntimeKtx" } androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastorePreferences" }+androidx-biometric = { module = "androidx.biometric:biometric", version.ref = "biometric" } androidx-exifinterface = { module = "androidx.exifinterface:exifinterface", version.ref = "exifinterface" }  # Jetpack Compose (BOM Managed)
library/build.gradle.kts
diff --git a/library/build.gradle.kts b/library/build.gradle.ktsindex 056d57ecef..74dc47b21f 100644--- a/library/build.gradle.kts+++ b/library/build.gradle.kts@@ -21,6 +21,10 @@ dependencies {      // room     implementRoom(libs)+    implementation("net.zetetic:sqlcipher-android:4.14.0@aar")+    implementation("androidx.sqlite:sqlite:2.6.2")+    implementation(libs.androidx.biometric)+    implementation(libs.androidx.fragment.ktx)      // work     implementation(libs.androidx.work.runtime.ktx)
library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt b/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.ktindex f6c5576938..5a43ff5248 100644--- a/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt+++ b/library/src/main/java/com/vayunmathur/library/util/RoomViewModel.kt@@ -1,6 +1,11 @@ package com.vayunmathur.library.util  import android.content.Context+import android.security.keystore.KeyGenParameterSpec+import android.security.keystore.KeyProperties+import android.util.Base64+import androidx.biometric.BiometricManager+import androidx.biometric.BiometricPrompt import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState@@ -12,6 +17,8 @@ import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue+import androidx.core.content.ContextCompat+import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.room.Dao@@ -38,6 +45,14 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.datetime.LocalTime import kotlinx.serialization.json.Json+import net.zetetic.database.sqlcipher.SupportOpenHelperFactory+import java.nio.charset.StandardCharsets+import java.security.KeyStore+import java.security.SecureRandom+import javax.crypto.Cipher+import javax.crypto.KeyGenerator+import javax.crypto.SecretKey+import javax.crypto.spec.GCMParameterSpec import kotlin.math.max import kotlin.math.min import kotlin.reflect.KClass@@ -347,13 +362,20 @@ suspend inline fun <reified E : DatabaseItem> TrueDao<E>.getNullable(id: Long):  val databases: MutableMap<KClass<*>, RoomDatabase> = mutableMapOf() -inline fun <reified T: RoomDatabase> Context.buildDatabase(migrations: List<Migration> = emptyList()): T {+inline fun <reified T: RoomDatabase> Context.buildDatabase(migrations: List<Migration> = emptyList(), encryptionPassword: String? = null): T {+    if(encryptionPassword != null) {+        System.loadLibrary("sqlcipher")+    }     if(databases[T::class] == null) {-        databases[T::class] = Room.databaseBuilder(+        val builder = Room.databaseBuilder(             this,             T::class.java,             "passwords-db"-        ).addMigrations(*migrations.toTypedArray()).build()+        ).addMigrations(*migrations.toTypedArray())+        if(encryptionPassword != null) {+            builder.openHelperFactory(SupportOpenHelperFactory(encryptionPassword.toByteArray(StandardCharsets.UTF_8)))+        }+        databases[T::class] = builder.build()     }     return databases[T::class]!! as T }@@ -389,4 +411,134 @@ class DefaultConverters {     fun fromLocalTime(value: LocalTime) = value.toSecondOfDay()     @TypeConverter     fun toLocalTime(value: Int) = LocalTime.fromSecondOfDay(value)-}\ No newline at end of file+}++class BiometricDatabaseHelper(val context: Context) {+    private val keyStoreAlias = "db_auth_key"+    private val sharedPrefsName = "secure_prefs"+    private val passphraseKey = "encrypted_passphrase"+    private val ivKey = "passphrase_iv"++    fun isKeyGenerated(): Boolean {+        val keyStore = KeyStore.getInstance("AndroidKeyStore")+        keyStore.load(null)+        return keyStore.containsAlias(keyStoreAlias)+    }++    fun generateBiometricKey() {+        val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")+        val builder = KeyGenParameterSpec.Builder(+            keyStoreAlias,+            KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT+        )+            .setBlockModes(KeyProperties.BLOCK_MODE_GCM)+            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)+            .setUserAuthenticationRequired(true)+            .setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG)+            .build()++        keyGenerator.init(builder)+        keyGenerator.generateKey()+    }++    private fun getSecretKey(): SecretKey {+        val keyStore = KeyStore.getInstance("AndroidKeyStore")+        keyStore.load(null)+        return keyStore.getKey(keyStoreAlias, null) as SecretKey+    }++    fun createAndStorePassphrase(cipher: Cipher): String {+        val random = SecureRandom()+        val passphraseBytes = ByteArray(32)+        random.nextBytes(passphraseBytes)+        val passphrase = Base64.encodeToString(passphraseBytes, Base64.NO_WRAP)++        val encryptedBytes = cipher.doFinal(passphrase.toByteArray(StandardCharsets.UTF_8))+        val iv = cipher.iv++        val prefs = context.getSharedPreferences(sharedPrefsName, Context.MODE_PRIVATE)+        prefs.edit()+            .putString(passphraseKey, Base64.encodeToString(encryptedBytes, Base64.NO_WRAP))+            .putString(ivKey, Base64.encodeToString(iv, Base64.NO_WRAP))+            .apply()++        return passphrase+    }++    fun decryptPassphrase(cipher: Cipher): String {+        val prefs = context.getSharedPreferences(sharedPrefsName, Context.MODE_PRIVATE)+        val encryptedPassphrase = prefs.getString(passphraseKey, null) ?: throw Exception("Passphrase not found")+        val encryptedBytes = Base64.decode(encryptedPassphrase, Base64.NO_WRAP)+        val decryptedBytes = cipher.doFinal(encryptedBytes)+        return String(decryptedBytes, StandardCharsets.UTF_8)+    }++    fun getCipherForEncryption(): Cipher {+        val cipher = Cipher.getInstance("${KeyProperties.KEY_ALGORITHM_AES}/${KeyProperties.BLOCK_MODE_GCM}/${KeyProperties.ENCRYPTION_PADDING_NONE}")+        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey())+        return cipher+    }++    fun getCipherForDecryption(): Cipher {+        val prefs = context.getSharedPreferences(sharedPrefsName, Context.MODE_PRIVATE)+        val ivBase64 = prefs.getString(ivKey, null) ?: throw Exception("IV not found")+        val iv = Base64.decode(ivBase64, Base64.NO_WRAP)+        val cipher = Cipher.getInstance("${KeyProperties.KEY_ALGORITHM_AES}/${KeyProperties.BLOCK_MODE_GCM}/${KeyProperties.ENCRYPTION_PADDING_NONE}")+        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(), GCMParameterSpec(128, iv))+        return cipher+    }+}++fun unlockDatabaseWithBiometrics(+    activity: FragmentActivity,+    onSuccess: (String) -> Unit,+    onFailure: () -> Unit+) {+    val helper = BiometricDatabaseHelper(activity)+    val executor = ContextCompat.getMainExecutor(activity)++    if (!helper.isKeyGenerated()) {+        helper.generateBiometricKey()+        val biometricPrompt = BiometricPrompt(activity, executor, object : BiometricPrompt.AuthenticationCallback() {+            override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {+                val cipher = result.cryptoObject?.cipher!!+                val passphrase = helper.createAndStorePassphrase(cipher)+                onSuccess(passphrase)+            }++            override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {+                onFailure()+            }+        })++        val promptInfo = BiometricPrompt.PromptInfo.Builder()+            .setTitle("Setup Secure Database")+            .setSubtitle("Authenticate to create your secure encryption key")+            .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)+            .setNegativeButtonText("Cancel")+            .build()++        biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(helper.getCipherForEncryption()))+    } else {+        val biometricPrompt = BiometricPrompt(activity, executor, object : BiometricPrompt.AuthenticationCallback() {+            override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {+                val cipher = result.cryptoObject?.cipher!!+                val passphrase = helper.decryptPassphrase(cipher)+                onSuccess(passphrase)+            }++            override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {+                onFailure()+            }+        })++        val promptInfo = BiometricPrompt.PromptInfo.Builder()+            .setTitle("Unlock Database")+            .setSubtitle("Authenticate to access your secure data")+            .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)+            .setNegativeButtonText("Cancel")+            .build()++        biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(helper.getCipherForDecryption()))+    }+}
passwords/build.gradle.kts
diff --git a/passwords/build.gradle.kts b/passwords/build.gradle.ktsindex cbec15dcaf..b02a4be3f0 100644--- a/passwords/build.gradle.kts+++ b/passwords/build.gradle.kts@@ -12,6 +12,7 @@ android {  dependencies {     implementRoom(libs)+    implementation(libs.androidx.fragment.ktx)      // CSV parsing library for Bitwarden CSV imports     implementation("com.github.doyaaaaaken:kotlin-csv-jvm:1.10.0")
passwords/src/main/java/com/vayunmathur/passwords/MainActivity.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/MainActivity.kt b/passwords/src/main/java/com/vayunmathur/passwords/MainActivity.ktindex 670d06fc09..b6ebc759e1 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/MainActivity.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/MainActivity.kt@@ -1,10 +1,10 @@ package com.vayunmathur.passwords  import android.os.Bundle-import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.runtime.Composable+import androidx.fragment.app.FragmentActivity import com.vayunmathur.library.util.NavKey import androidx.room.migration.Migration import com.vayunmathur.library.ui.DynamicTheme@@ -14,6 +14,7 @@ import com.vayunmathur.library.util.ListPage import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.library.util.unlockDatabaseWithBiometrics import com.vayunmathur.passwords.data.PasswordDatabase import com.vayunmathur.passwords.ui.MenuPage import com.vayunmathur.passwords.data.Password@@ -22,17 +23,26 @@ import com.vayunmathur.passwords.ui.PasswordPage import com.vayunmathur.passwords.ui.SettingsPage import kotlinx.serialization.Serializable -class MainActivity : ComponentActivity() {+class MainActivity : FragmentActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         enableEdgeToEdge()-        val db = buildDatabase<PasswordDatabase>()-        val viewModel = DatabaseViewModel(db,Password::class to db.passwordDao())-        setContent {-            DynamicTheme {-                Navigation(viewModel)++        unlockDatabaseWithBiometrics(+            activity = this,+            onSuccess = { passphrase ->+                val db = buildDatabase<PasswordDatabase>(encryptionPassword = passphrase)+                val viewModel = DatabaseViewModel(db,Password::class to db.passwordDao())+                setContent {+                    DynamicTheme {+                        Navigation(viewModel)+                    }+                }+            },+            onFailure = {+                finish()             }-        }+        )     } }