Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Make basic biometric keystore flow work (#846)
Leendert de Borst1868370d8ff1
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.ktindex 6d97e5435..476bc36b5 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt@@ -25,7 +25,7 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :private val vaultStore = VaultStore(AndroidStorageProvider(reactContext),- AndroidKeystoreProvider(reactContext, getFragmentActivity())+ AndroidKeystoreProvider(reactContext) { getFragmentActivity() })override fun getName(): String {diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.ktindex c4f0a8316..d9a77d61f 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt@@ -43,18 +43,31 @@ class VaultStore(// Check if biometric auth is enabled in auth methodsval authMethods = getAuthMethods()if (authMethods.contains(BIOMETRICS_AUTH_METHOD) && keystoreProvider.isBiometricAvailable()) {+ // Create a latch to wait for the callback+ val latch = java.util.concurrent.CountDownLatch(1)+ var error: Exception? = null+keystoreProvider.storeKey(key = base64EncryptionKey,object : KeystoreOperationCallback {override fun onSuccess(result: String) {Log.d(TAG, "Encryption key stored successfully with biometric protection")+ latch.countDown()}override fun onError(e: Exception) {Log.e(TAG, "Error storing encryption key with biometric protection", e)+ error = e+ latch.countDown()}})++ // Wait for the callback to complete+ latch.await()++ // Throw any error that occurred+ error?.let { throw it }}}@@ -68,8 +81,6 @@ class VaultStore(// Check if biometric auth is enabled in auth methodsval authMethods = getAuthMethods()- val contains = authMethods.contains(BIOMETRICS_AUTH_METHOD)- val available = keystoreProvider.isBiometricAvailable()if (authMethods.contains(BIOMETRICS_AUTH_METHOD) && keystoreProvider.isBiometricAvailable()) {keystoreProvider.retrieveKey(object : KeystoreOperationCallback {diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.ktindex 17cb8a9e6..3a08722e5 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.kt@@ -3,6 +3,8 @@ package net.aliasvault.app.vaultstore.keystoreproviderimport android.app.Activityimport android.content.Contextimport android.content.SharedPreferences+import android.os.Handler+import android.os.Looperimport android.security.keystore.KeyGenParameterSpecimport android.security.keystore.KeyPropertiesimport android.util.Base64@@ -22,9 +24,13 @@ import javax.crypto.spec.GCMParameterSpec/*** Android implementation of the keystore provider that uses Android's Keystore and Biometric APIs.*/-class AndroidKeystoreProvider(private val context: Context, private val FragmentActivity: FragmentActivity?) : KeystoreProvider {+class AndroidKeystoreProvider(+ private val context: Context,+ private val getCurrentActivity: () -> Activity?+) : KeystoreProvider {private val biometricManager = BiometricManager.from(context)private val executor: Executor = Executors.newSingleThreadExecutor()+ private val mainHandler = Handler(Looper.getMainLooper())private val TAG = "AndroidKeystoreProvider"private val KEYSTORE_ALIAS = "aliasvault_biometric_key"private val ENCRYPTED_KEY_PREF = "encrypted_vault_key"@@ -36,191 +42,207 @@ class AndroidKeystoreProvider(private val context: Context, private val Fragment}override fun storeKey(key: String, callback: KeystoreOperationCallback) {- try {- // Set up KeyStore- val keyStore = KeyStore.getInstance("AndroidKeyStore")- keyStore.load(null)-- // Create or get biometric key- if (!keyStore.containsAlias(KEYSTORE_ALIAS)) {- val keyGenerator = KeyGenerator.getInstance(- KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"- )-- val keySpec = KeyGenParameterSpec.Builder(- KEYSTORE_ALIAS,- KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT- )- .setBlockModes(KeyProperties.BLOCK_MODE_GCM)- .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)- .setUserAuthenticationRequired(true)+ mainHandler.post {+ try {+ val currentActivity = getCurrentActivity()+ if (currentActivity == null || !(currentActivity is FragmentActivity)) {+ callback.onError(Exception("No activity available for biometric authentication"))+ return@post+ }++ // Set up KeyStore+ val keyStore = KeyStore.getInstance("AndroidKeyStore")+ keyStore.load(null)++ // Create or get biometric key+ if (!keyStore.containsAlias(KEYSTORE_ALIAS)) {+ val keyGenerator = KeyGenerator.getInstance(+ KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"+ )++ val keySpec = KeyGenParameterSpec.Builder(+ KEYSTORE_ALIAS,+ KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT+ )+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)+ .setUserAuthenticationRequired(true)+ .build()++ keyGenerator.init(keySpec)+ keyGenerator.generateKey()+ }++ // Get the created key+ val secretKey = keyStore.getKey(KEYSTORE_ALIAS, null) as SecretKey++ // Create BiometricPrompt+ val promptInfo = BiometricPrompt.PromptInfo.Builder()+ .setTitle("Store Encryption Key")+ .setSubtitle("Authenticate to securely store your encryption key in the Android Keystore. This enables biometric access to your vault.")+ .setNegativeButtonText("Cancel").build()- keyGenerator.init(keySpec)- keyGenerator.generateKey()- }-- // Get the created key- val secretKey = keyStore.getKey(KEYSTORE_ALIAS, null) as SecretKey-- // Create BiometricPrompt- val promptInfo = BiometricPrompt.PromptInfo.Builder()- .setTitle("Protect Vault Key")- .setSubtitle("Authenticate to protect your vault encryption key")- .setNegativeButtonText("Cancel")- .build()-- val biometricPrompt = BiometricPrompt(FragmentActivity!!, executor,- object : BiometricPrompt.AuthenticationCallback() {- override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {- try {- // Get the cipher from the result- val cipher = result.cryptoObject?.cipher ?: throw Exception("Cipher is null")-- // Encrypt the key- val encryptedKey = cipher.doFinal(key.toByteArray())- val iv = cipher.iv-- // Combine IV and encrypted key- val byteBuffer = ByteBuffer.allocate(iv.size + encryptedKey.size)- byteBuffer.put(iv)- byteBuffer.put(encryptedKey)- val combined = byteBuffer.array()-- // Store encrypted key in SharedPreferences- val encryptedKeyB64 = Base64.encodeToString(combined, Base64.DEFAULT)- val prefs = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)- prefs.edit().putString(ENCRYPTED_KEY_PREF, encryptedKeyB64).apply()-- Log.d(TAG, "Encryption key stored successfully")- callback.onSuccess("Key stored successfully")- } catch (e: Exception) {- Log.e(TAG, "Error storing encryption key", e)- callback.onError(e)+ val biometricPrompt = BiometricPrompt(currentActivity, executor,+ object : BiometricPrompt.AuthenticationCallback() {+ override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {+ try {+ // Get the cipher from the result+ val cipher = result.cryptoObject?.cipher ?: throw Exception("Cipher is null")++ // Encrypt the key+ val encryptedKey = cipher.doFinal(key.toByteArray())+ val iv = cipher.iv++ // Combine IV and encrypted key+ val byteBuffer = ByteBuffer.allocate(iv.size + encryptedKey.size)+ byteBuffer.put(iv)+ byteBuffer.put(encryptedKey)+ val combined = byteBuffer.array()++ // Store encrypted key in SharedPreferences+ val encryptedKeyB64 = Base64.encodeToString(combined, Base64.DEFAULT)+ val prefs = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)+ prefs.edit().putString(ENCRYPTED_KEY_PREF, encryptedKeyB64).apply()++ Log.d(TAG, "Encryption key stored successfully")+ callback.onSuccess("Key stored successfully")+ } catch (e: Exception) {+ Log.e(TAG, "Error storing encryption key", e)+ callback.onError(e)+ }}- }- override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {- Log.e(TAG, "Authentication error: $errString")- callback.onError(Exception("Authentication error: $errString"))- }+ override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {+ Log.e(TAG, "Authentication error: $errString")+ callback.onError(Exception("Authentication error: $errString"))+ }- override fun onAuthenticationFailed() {- Log.e(TAG, "Authentication failed")- }- })+ override fun onAuthenticationFailed() {+ Log.e(TAG, "Authentication failed")+ }+ })- // Initialize cipher for encryption- val cipher = Cipher.getInstance(- "${KeyProperties.KEY_ALGORITHM_AES}/" +- "${KeyProperties.BLOCK_MODE_GCM}/" +- KeyProperties.ENCRYPTION_PADDING_NONE- )- cipher.init(Cipher.ENCRYPT_MODE, secretKey)+ // Initialize cipher for encryption+ val cipher = Cipher.getInstance(+ "${KeyProperties.KEY_ALGORITHM_AES}/" ++ "${KeyProperties.BLOCK_MODE_GCM}/" ++ KeyProperties.ENCRYPTION_PADDING_NONE+ )+ cipher.init(Cipher.ENCRYPT_MODE, secretKey)- // Show biometric prompt- biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))+ // Show biometric prompt+ biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))- } catch (e: Exception) {- Log.e(TAG, "Error in biometric key storage", e)- callback.onError(e)+ } catch (e: Exception) {+ Log.e(TAG, "Error in biometric key storage", e)+ callback.onError(e)+ }}}override fun retrieveKey(callback: KeystoreOperationCallback) {- try {- // Check if we have a stored key- val prefs = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)- val encryptedKeyB64 = prefs.getString(ENCRYPTED_KEY_PREF, null)+ mainHandler.post {+ try {+ val currentActivity = getCurrentActivity()+ if (currentActivity == null || !(currentActivity is FragmentActivity)) {+ callback.onError(Exception("No activity available for biometric authentication"))+ return@post+ }++ // Check if we have a stored key+ val prefs = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)+ val encryptedKeyB64 = prefs.getString(ENCRYPTED_KEY_PREF, null)++ if (encryptedKeyB64 == null) {+ callback.onError(Exception("No encryption key found"))+ return@post+ }++ // Set up KeyStore+ val keyStore = KeyStore.getInstance("AndroidKeyStore")+ keyStore.load(null)++ // Check if key exists+ if (!keyStore.containsAlias(KEYSTORE_ALIAS)) {+ Log.e(TAG, "Keystore key not found")+ callback.onError(Exception("Keystore key not found"))+ return@post+ }++ // Get the key+ val secretKey = keyStore.getKey(KEYSTORE_ALIAS, null) as SecretKey++ // Create BiometricPrompt+ val promptInfo = BiometricPrompt.PromptInfo.Builder()+ .setTitle("Unlock Vault")+ .setSubtitle("Authenticate to access your vault")+ .setNegativeButtonText("Cancel")+ .build()- if (encryptedKeyB64 == null) {- callback.onError(Exception("No encryption key found"))- return- }+ val biometricPrompt = BiometricPrompt(currentActivity, executor,+ object : BiometricPrompt.AuthenticationCallback() {+ override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {+ try {+ // Get the cipher from the result+ val cipher = result.cryptoObject?.cipher ?: throw Exception("Cipher is null")- // Set up KeyStore- val keyStore = KeyStore.getInstance("AndroidKeyStore")- keyStore.load(null)+ // Decode combined data+ val combined = Base64.decode(encryptedKeyB64, Base64.DEFAULT)- // Check if key exists- if (!keyStore.containsAlias(KEYSTORE_ALIAS)) {- Log.e(TAG, "Keystore key not found")- callback.onError(Exception("Keystore key not found"))- return- }+ // Extract IV and encrypted data+ val byteBuffer = ByteBuffer.wrap(combined)++ // GCM typically uses 12 bytes for IV+ val iv = ByteArray(12)+ byteBuffer.get(iv)++ // Get remaining bytes as ciphertext+ val encryptedBytes = ByteArray(byteBuffer.remaining())+ byteBuffer.get(encryptedBytes)++ // Decrypt the key+ val decryptedKey = cipher.doFinal(encryptedBytes)- // Get the key- val secretKey = keyStore.getKey(KEYSTORE_ALIAS, null) as SecretKey-- // Create BiometricPrompt- val promptInfo = BiometricPrompt.PromptInfo.Builder()- .setTitle("Unlock Vault")- .setSubtitle("Authenticate to access your vault")- .setNegativeButtonText("Cancel")- .build()-- val biometricPrompt = BiometricPrompt(FragmentActivity!!, executor,- object : BiometricPrompt.AuthenticationCallback() {- override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {- try {- // Get the cipher from the result- val cipher = result.cryptoObject?.cipher ?: throw Exception("Cipher is null")-- // Decode combined data- val combined = Base64.decode(encryptedKeyB64, Base64.DEFAULT)-- // Extract IV and encrypted data- val byteBuffer = ByteBuffer.wrap(combined)-- // GCM typically uses 12 bytes for IV- val iv = ByteArray(12)- byteBuffer.get(iv)-- // Get remaining bytes as ciphertext- val encryptedBytes = ByteArray(byteBuffer.remaining())- byteBuffer.get(encryptedBytes)-- // Decrypt the key- val decryptedKey = cipher.doFinal(encryptedBytes)-- Log.d(TAG, "Encryption key retrieved successfully")- callback.onSuccess(String(decryptedKey))- } catch (e: Exception) {- Log.e(TAG, "Error retrieving encryption key", e)- callback.onError(e)+ Log.d(TAG, "Encryption key retrieved successfully")+ callback.onSuccess(String(decryptedKey))+ } catch (e: Exception) {+ Log.e(TAG, "Error retrieving encryption key", e)+ callback.onError(e)+ }}- }-- override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {- Log.e(TAG, "Authentication error: $errString")- callback.onError(Exception("Authentication error: $errString"))- }-- override fun onAuthenticationFailed() {- Log.e(TAG, "Authentication failed")- }- })-- // Initialize cipher for decryption with IV from stored encrypted key- val combined = Base64.decode(encryptedKeyB64, Base64.DEFAULT)- val byteBuffer = ByteBuffer.wrap(combined)- val iv = ByteArray(12)- byteBuffer.get(iv)-- val cipher = Cipher.getInstance(- "${KeyProperties.KEY_ALGORITHM_AES}/" +- "${KeyProperties.BLOCK_MODE_GCM}/" +- KeyProperties.ENCRYPTION_PADDING_NONE- )- val spec = GCMParameterSpec(128, iv)- cipher.init(Cipher.DECRYPT_MODE, secretKey, spec)-- // Show biometric prompt- biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))- } catch (e: Exception) {- Log.e(TAG, "Error in biometric key retrieval", e)- callback.onError(e)+ override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {+ Log.e(TAG, "Authentication error: $errString")+ callback.onError(Exception("Authentication error: $errString"))+ }++ override fun onAuthenticationFailed() {+ Log.e(TAG, "Authentication failed")+ }+ })++ // Initialize cipher for decryption with IV from stored encrypted key+ val combined = Base64.decode(encryptedKeyB64, Base64.DEFAULT)+ val byteBuffer = ByteBuffer.wrap(combined)+ val iv = ByteArray(12)+ byteBuffer.get(iv)++ val cipher = Cipher.getInstance(+ "${KeyProperties.KEY_ALGORITHM_AES}/" ++ "${KeyProperties.BLOCK_MODE_GCM}/" ++ KeyProperties.ENCRYPTION_PADDING_NONE+ )+ val spec = GCMParameterSpec(128, iv)+ cipher.init(Cipher.DECRYPT_MODE, secretKey, spec)++ // Show biometric prompt+ biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))++ } catch (e: Exception) {+ Log.e(TAG, "Error in biometric key retrieval", e)+ callback.onError(e)+ }}}diff --git a/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.kt b/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.ktindex 935a2ef8c..272cee306 100644--- a/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.kt+++ b/apps/mobile-app/android/app/src/test/java/net/aliasvault/app/nativevaultmanager/VaultStoreTest.kt@@ -8,7 +8,6 @@ import org.robolectric.annotation.Configimport net.aliasvault.app.vaultstore.VaultStoreimport net.aliasvault.app.vaultstore.storageprovider.TestStorageProviderimport net.aliasvault.app.vaultstore.keystoreprovider.TestKeystoreProvider-import java.util.Dateimport kotlin.test.*@RunWith(RobolectricTestRunner::class)