Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Port java to kotlin (#771)
Leendert de Borstd1b3e97c6b46
diff --git a/mobile-app/android/app/src/main/java/net/aliasvault/app/AutofillService.kt b/mobile-app/android/app/src/main/java/net/aliasvault/app/AutofillService.ktindex e3b0f66a2..b92b3d399 100644--- a/mobile-app/android/app/src/main/java/net/aliasvault/app/AutofillService.kt+++ b/mobile-app/android/app/src/main/java/net/aliasvault/app/AutofillService.kt@@ -38,9 +38,7 @@ import android.view.Viewimport android.view.autofill.AutofillIdimport android.view.autofill.AutofillValueimport android.widget.RemoteViews-import com.facebook.react.bridge.Argumentsimport net.aliasvault.app.credentialmanager.Credential-import net.aliasvault.app.credentialmanager.CredentialManagerModuleimport net.aliasvault.app.credentialmanager.SharedCredentialStoreimport net.aliasvault.app.credentialmanager.SharedCredentialStore.CryptoOperationCallbackimport org.json.JSONArray@@ -76,12 +74,7 @@ class AutofillService : AutofillService() {return}- // Since we're in a Service, we don't have direct access to a FragmentActivity- // Option 1: Launch an activity to authenticate and then filllaunchActivityForAutofill(fieldFinder, callback)-- // Option 2: For immediate filling without authentication (simplified for demo purposes)- //createMockAutofillResponse(fieldFinder, callback)}override fun onSaveRequest(request: SaveRequest, callback: SaveCallback) {@@ -95,13 +88,14 @@ class AutofillService : AutofillService() {}private fun launchActivityForAutofill(fieldFinder: FieldFinder, callback: FillCallback) {- Log.d(TAG, "Retrieving credentials for autofill")+ Log.d(TAG, "Launching activity for autofill authentication")// Get the shared credential storeval store = SharedCredentialStore.getInstance(applicationContext)- // Try to retrieve all credentials from the store- store.getAllCredentials(null, object : CryptoOperationCallback {+ // Try to retrieve all credentials using the cached key first, which if available+ // does not require biometric authentication.+ if (store.tryGetAllCredentialsWithCachedKey(object : CryptoOperationCallback {override fun onSuccess(jsonString: String) {try {val jsonArray = JSONArray(jsonString)@@ -143,17 +137,32 @@ class AutofillService : AutofillService() {override fun onError(e: Exception) {Log.e(TAG, "Error getting credentials", e)callback.onSuccess(null)-- // Fallback to launching the activity for manual selection- val intent = Intent(this@AutofillService, MainActivity::class.java).apply {- putExtra("AUTOFILL_REQUEST", true)- addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)- }- startActivity(intent)}- })+ })) {+ // Successfully used cached key - method returns true+ Log.d(TAG, "Successfully retrieved credentials with cached key")+ } else {+ // No cached key available, we need to launch the AliasVault app in order to+ // load the encryption key from biometric keystore.+ Log.d(TAG, "No cached key available, launching activity for authentication")++ // Create an intent to launch MainActivity with autofill flags+ // TODO: detect "AUTOFILL_REQUEST" when app opens to show proper help text to+ // indicate vault should be unlocked in order for autofill to work. With dismiss+ // close buttons etc for better UX.+ val intent = Intent(this, MainActivity::class.java).apply {+ // Add flags to launch as a new task+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ // Add extra data to indicate this is for autofill+ putExtra("AUTOFILL_REQUEST", true)+ }++ // Start the activity+ startActivity(intent)+ }}+ // Helper method to create a dataset from a credentialprivate fun addDatasetForCredential(responseBuilder: FillResponse.Builder,fieldFinder: FieldFinder,@@ -179,32 +188,6 @@ class AutofillService : AutofillService() {responseBuilder.addDataset(dataSetBuilder.build())}- // This method demonstrates what the response would look like if we had credentials- private fun createMockAutofillResponse(fieldFinder: FieldFinder, callback: FillCallback) {- // Create a mock credential for demonstration- val credential = Credential("[email protected]", "password123", "Example Service")-- // Build a response with the credential- val responseBuilder = FillResponse.Builder()-- // Create a dataset with the credential- val presentation = RemoteViews(packageName, android.R.layout.simple_list_item_1)- presentation.setTextViewText(android.R.id.text1, "AliasVault: ${credential.service}")-- val dataSetBuilder = Dataset.Builder(presentation)-- // Add autofill values for all fields - fill everything with either username or password- // depending on if the field appears to be a password field- for (field in fieldFinder.autofillableFields) {- val isPassword = field.second- val value = if (isPassword) credential.password else credential.username- dataSetBuilder.setValue(field.first, AutofillValue.forText(value))- }-- responseBuilder.addDataset(dataSetBuilder.build())- callback.onSuccess(responseBuilder.build())- }-private fun parseStructure(structure: AssistStructure, fieldFinder: FieldFinder) {val nodeCount = structure.windowNodeCountfor (i in 0 until nodeCount) {diff --git a/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt b/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.ktindex 5e4ecc43e..1e66fbf78 100644--- a/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt+++ b/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt@@ -24,7 +24,10 @@ class MainActivity : ReactActivity() {SplashScreenManager.registerOnActivity(this)// @generated end expo-splashscreen- // Initialize autofill service+ // Initialize autofill service, this opens the set_autofill_service setting screen+ // to instruct user to enable AliasVault as autofill provider.+ // TODO: this should be triggerable from React Native instead so we can better control flow+ // of when to ask the user to enable native system autofill.startActivity(Intent(Settings.ACTION_REQUEST_SET_AUTOFILL_SERVICE).apply {data = Uri.parse("package:net.aliasvault.app")})diff --git a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/Credential.java b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/Credential.javadeleted file mode 100644index a7dd69525..000000000--- a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/Credential.java+++ /dev/null@@ -1,25 +0,0 @@-package net.aliasvault.app.credentialmanager;--public class Credential {- private String username;- private String password;- private String service;-- public Credential(String username, String password, String service) {- this.username = username;- this.password = password;- this.service = service;- }-- public String getUsername() {- return username;- }-- public String getPassword() {- return password;- }-- public String getService() {- return service;- }-}\ No newline at end of filediff --git a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/Credential.kt b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/Credential.ktnew file mode 100644index 000000000..4bafbb768--- /dev/null+++ b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/Credential.kt@@ -0,0 +1,7 @@+package net.aliasvault.app.credentialmanager++data class Credential(+ val username: String,+ val password: String,+ val service: String+)\ No newline at end of filediff --git a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerModule.java b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerModule.javadeleted file mode 100644index 657757c91..000000000--- a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerModule.java+++ /dev/null@@ -1,142 +0,0 @@-package net.aliasvault.app.credentialmanager;--import android.app.Activity;-import android.util.Log;--import androidx.annotation.NonNull;-import androidx.fragment.app.FragmentActivity;--import com.facebook.react.bridge.Arguments;-import com.facebook.react.bridge.Promise;-import com.facebook.react.bridge.ReactApplicationContext;-import com.facebook.react.bridge.ReactContextBaseJavaModule;-import com.facebook.react.bridge.ReactMethod;-import com.facebook.react.bridge.UiThreadUtil;-import com.facebook.react.bridge.WritableArray;-import com.facebook.react.bridge.WritableMap;--import org.json.JSONArray;-import org.json.JSONObject;--import java.util.List;--public class CredentialManagerModule extends ReactContextBaseJavaModule {- private static final String TAG = "CredentialManagerModule";- private final ReactApplicationContext reactContext;-- public CredentialManagerModule(ReactApplicationContext reactContext) {- super(reactContext);- this.reactContext = reactContext;- }-- @Override- public String getName() {- return "CredentialManager";- }-- private FragmentActivity getFragmentActivity() {- Activity activity = getCurrentActivity();- if (activity instanceof FragmentActivity) {- return (FragmentActivity) activity;- }- return null;- }-- @ReactMethod- public void addCredential(final String username, final String password, final String service, final Promise promise) {- UiThreadUtil.runOnUiThread(new Runnable() {- @Override- public void run() {- try {- FragmentActivity activity = getFragmentActivity();- if (activity == null) {- promise.reject("ERR_ACTIVITY", "Activity is not available");- return;- }-- SharedCredentialStore store = SharedCredentialStore.getInstance(reactContext);- Credential credential = new Credential(username, password, service);-- store.saveCredential(activity, credential, new SharedCredentialStore.CryptoOperationCallback() {- @Override- public void onSuccess(String result) {- promise.resolve(true);- }-- @Override- public void onError(Exception e) {- Log.e(TAG, "Error adding credential", e);- promise.reject("ERR_ADD_CREDENTIAL", "Failed to add credential: " + e.getMessage(), e);- }- });- } catch (Exception e) {- Log.e(TAG, "Error preparing to add credential", e);- promise.reject("ERR_ADD_CREDENTIAL", "Failed to prepare adding credential: " + e.getMessage(), e);- }- }- });- }-- @ReactMethod- public void getCredentials(final Promise promise) {- UiThreadUtil.runOnUiThread(new Runnable() {- @Override- public void run() {- try {- FragmentActivity activity = getFragmentActivity();- if (activity == null) {- promise.reject("ERR_ACTIVITY", "Activity is not available");- return;- }-- SharedCredentialStore store = SharedCredentialStore.getInstance(reactContext);-- store.getAllCredentials(activity, new SharedCredentialStore.CryptoOperationCallback() {- @Override- public void onSuccess(String jsonString) {- try {- JSONArray jsonArray = new JSONArray(jsonString);- WritableArray credentialsArray = Arguments.createArray();-- for (int i = 0; i < jsonArray.length(); i++) {- JSONObject jsonObject = jsonArray.getJSONObject(i);- WritableMap credentialMap = Arguments.createMap();- credentialMap.putString("username", jsonObject.getString("username"));- credentialMap.putString("password", jsonObject.getString("password"));- credentialMap.putString("service", jsonObject.getString("service"));- credentialsArray.pushMap(credentialMap);- }-- promise.resolve(credentialsArray);- } catch (Exception e) {- Log.e(TAG, "Error parsing credentials", e);- promise.reject("ERR_PARSE_CREDENTIALS", "Failed to parse credentials: " + e.getMessage(), e);- }- }-- @Override- public void onError(Exception e) {- Log.e(TAG, "Error getting credentials", e);- promise.reject("ERR_GET_CREDENTIALS", "Failed to get credentials: " + e.getMessage(), e);- }- });- } catch (Exception e) {- Log.e(TAG, "Error preparing to get credentials", e);- promise.reject("ERR_GET_CREDENTIALS", "Failed to prepare getting credentials: " + e.getMessage(), e);- }- }- });- }-- @ReactMethod- public void clearCredentials(final Promise promise) {- try {- SharedCredentialStore store = SharedCredentialStore.getInstance(reactContext);- store.clearAllData();- promise.resolve(true);- } catch (Exception e) {- Log.e(TAG, "Error clearing credentials", e);- promise.reject("ERR_CLEAR_CREDENTIALS", "Failed to clear credentials: " + e.getMessage(), e);- }- }-}\ No newline at end of filediff --git a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerModule.kt b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerModule.ktnew file mode 100644index 000000000..267de80df--- /dev/null+++ b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerModule.kt@@ -0,0 +1,130 @@+package net.aliasvault.app.credentialmanager;++import android.app.Activity;+import android.util.Log;++import androidx.annotation.NonNull;+import androidx.fragment.app.FragmentActivity;++import com.facebook.react.bridge.Arguments;+import com.facebook.react.bridge.Promise;+import com.facebook.react.bridge.ReactApplicationContext;+import com.facebook.react.bridge.ReactContextBaseJavaModule;+import com.facebook.react.bridge.ReactMethod;+import com.facebook.react.bridge.UiThreadUtil;+import com.facebook.react.bridge.WritableArray;+import com.facebook.react.bridge.WritableMap;++import org.json.JSONArray;+import org.json.JSONObject;++import java.util.List;++class CredentialManagerModule(private val reactContext: ReactApplicationContext) :+ ReactContextBaseJavaModule(reactContext) {++ companion object {+ private const val TAG = "CredentialManagerModule"+ }++ override fun getName(): String {+ return "CredentialManager"+ }++ private fun getFragmentActivity(): FragmentActivity? {+ val activity = currentActivity+ return if (activity is FragmentActivity) {+ activity+ } else {+ null+ }+ }++ @ReactMethod+ fun addCredential(username: String, password: String, service: String, promise: Promise) {+ UiThreadUtil.runOnUiThread {+ try {+ val activity = getFragmentActivity()+ if (activity == null) {+ promise.reject("ERR_ACTIVITY", "Activity is not available")+ return@runOnUiThread+ }++ val store = SharedCredentialStore.getInstance(reactContext)+ val credential = Credential(username, password, service)++ store.saveCredential(activity, credential, object : SharedCredentialStore.CryptoOperationCallback {+ override fun onSuccess(result: String) {+ promise.resolve(true)+ }++ override fun onError(e: Exception) {+ Log.e(TAG, "Error adding credential", e)+ promise.reject("ERR_ADD_CREDENTIAL", "Failed to add credential: ${e.message}", e)+ }+ })+ } catch (e: Exception) {+ Log.e(TAG, "Error preparing to add credential", e)+ promise.reject("ERR_ADD_CREDENTIAL", "Failed to prepare adding credential: ${e.message}", e)+ }+ }+ }++ @ReactMethod+ fun getCredentials(promise: Promise) {+ UiThreadUtil.runOnUiThread {+ try {+ val activity = getFragmentActivity()+ if (activity == null) {+ promise.reject("ERR_ACTIVITY", "Activity is not available")+ return@runOnUiThread+ }++ val store = SharedCredentialStore.getInstance(reactContext)++ store.getAllCredentials(activity, object : SharedCredentialStore.CryptoOperationCallback {+ override fun onSuccess(jsonString: String) {+ try {+ val jsonArray = JSONArray(jsonString)+ val credentialsArray = Arguments.createArray()++ for (i in 0 until jsonArray.length()) {+ val jsonObject = jsonArray.getJSONObject(i)+ val credentialMap = Arguments.createMap()+ credentialMap.putString("username", jsonObject.getString("username"))+ credentialMap.putString("password", jsonObject.getString("password"))+ credentialMap.putString("service", jsonObject.getString("service"))+ credentialsArray.pushMap(credentialMap)+ }++ promise.resolve(credentialsArray)+ } catch (e: Exception) {+ Log.e(TAG, "Error parsing credentials", e)+ promise.reject("ERR_PARSE_CREDENTIALS", "Failed to parse credentials: ${e.message}", e)+ }+ }++ override fun onError(e: Exception) {+ Log.e(TAG, "Error getting credentials", e)+ promise.reject("ERR_GET_CREDENTIALS", "Failed to get credentials: ${e.message}", e)+ }+ })+ } catch (e: Exception) {+ Log.e(TAG, "Error preparing to get credentials", e)+ promise.reject("ERR_GET_CREDENTIALS", "Failed to prepare getting credentials: ${e.message}", e)+ }+ }+ }++ @ReactMethod+ fun clearCredentials(promise: Promise) {+ try {+ val store = SharedCredentialStore.getInstance(reactContext)+ store.clearAllData()+ promise.resolve(true)+ } catch (e: Exception) {+ Log.e(TAG, "Error clearing credentials", e)+ promise.reject("ERR_CLEAR_CREDENTIALS", "Failed to clear credentials: ${e.message}", e)+ }+ }+}\ No newline at end of filediff --git a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerPackage.java b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerPackage.javadeleted file mode 100644index f6dd53fad..000000000--- a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerPackage.java+++ /dev/null@@ -1,24 +0,0 @@-package net.aliasvault.app.credentialmanager;--import com.facebook.react.ReactPackage;-import com.facebook.react.bridge.NativeModule;-import com.facebook.react.bridge.ReactApplicationContext;-import com.facebook.react.uimanager.ViewManager;--import java.util.ArrayList;-import java.util.Collections;-import java.util.List;--public class CredentialManagerPackage implements ReactPackage {- @Override- public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {- return Collections.emptyList();- }-- @Override- public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {- List<NativeModule> modules = new ArrayList<>();- modules.add(new CredentialManagerModule(reactContext));- return modules;- }-}\ No newline at end of filediff --git a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerPackage.kt b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerPackage.ktnew file mode 100644index 000000000..6fb2044f8--- /dev/null+++ b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerPackage.kt@@ -0,0 +1,16 @@+package net.aliasvault.app.credentialmanager++import com.facebook.react.ReactPackage+import com.facebook.react.bridge.NativeModule+import com.facebook.react.bridge.ReactApplicationContext+import com.facebook.react.uimanager.ViewManager++class CredentialManagerPackage : ReactPackage {+ override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {+ return emptyList()+ }++ override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {+ return listOf(CredentialManagerModule(reactContext))+ }+}diff --git a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/SharedCredentialStore.java b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/SharedCredentialStore.javadeleted file mode 100644index cf26162ee..000000000--- a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/SharedCredentialStore.java+++ /dev/null@@ -1,531 +0,0 @@-package net.aliasvault.app.credentialmanager;--import android.content.Context;-import android.content.SharedPreferences;-import android.security.keystore.KeyGenParameterSpec;-import android.security.keystore.KeyProperties;-import android.util.Base64;-import android.util.Log;-import java.nio.ByteBuffer;-import java.security.KeyStore;-import java.security.SecureRandom;--import androidx.biometric.BiometricPrompt;-import androidx.core.content.ContextCompat;-import androidx.fragment.app.FragmentActivity;--import org.json.JSONArray;-import org.json.JSONException;-import org.json.JSONObject;--import java.nio.charset.StandardCharsets;-import java.util.ArrayList;-import java.util.List;-import java.util.concurrent.Executor;-import java.util.concurrent.Executors;--import javax.crypto.Cipher;-import javax.crypto.KeyGenerator;-import javax.crypto.SecretKey;-import javax.crypto.spec.GCMParameterSpec;-import javax.crypto.spec.SecretKeySpec;--public class SharedCredentialStore {- private static final String TAG = "SharedCredentialStore";- private static final String SHARED_PREFS_NAME = "net.aliasvault.credentials";- private static final String CREDENTIALS_KEY = "stored_credentials";- private static final String KEYSTORE_ALIAS = "net.aliasvault.encryption_key";- private static final String ENCRYPTED_KEY_PREF = "encrypted_key";-- private static SharedCredentialStore instance;- private final Context appContext;-- // Cache for encryption key during the lifetime of this instance- private byte[] encryptionKey;- private final Executor executor;-- // Interface for operations that need callbacks- public interface CryptoOperationCallback {- void onSuccess(String result);- void onError(Exception e);- }-- private SharedCredentialStore(Context context) {- this.appContext = context.getApplicationContext();- this.executor = Executors.newSingleThreadExecutor();- }-- public static synchronized SharedCredentialStore getInstance(Context context) {- if (instance == null) {- instance = new SharedCredentialStore(context);- }- return instance;- }-- /**- * Get or create encryption key using biometric authentication- */- public void getEncryptionKey(FragmentActivity activity, final CryptoOperationCallback callback) {- // If key is already in memory, use it- if (encryptionKey != null) {- Log.d(TAG, "Using cached encryption key");- callback.onSuccess("Key available");- return;- }-- // Check if we have a stored key- SharedPreferences prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);- String encryptedKeyB64 = prefs.getString(ENCRYPTED_KEY_PREF, null);-- if (encryptedKeyB64 == null) {- // No key exists, create a new one- createNewEncryptionKey(activity, callback);- } else {- // Key exists, retrieve it with biometric auth- retrieveEncryptionKey(activity, encryptedKeyB64, callback);- }- }-- /**- * Create a new random encryption key and protect it with biometrics- */- private void createNewEncryptionKey(FragmentActivity activity, final CryptoOperationCallback callback) {- try {- // Generate a random 32-byte key for AES-256- SecureRandom secureRandom = new SecureRandom();- byte[] randomKey = new byte[32];- secureRandom.nextBytes(randomKey);-- // Cache the key- encryptionKey = randomKey;-- // Store the key protected by biometric authentication- storeKeyWithBiometricProtection(activity, randomKey, callback);- } catch (Exception e) {- Log.e(TAG, "Error creating encryption key", e);- callback.onError(e);- }- }-- /**- * Store the encryption key protected by biometric authentication- */- private void storeKeyWithBiometricProtection(FragmentActivity activity, final byte[] keyToStore,- final CryptoOperationCallback callback) {- try {- // Set up KeyStore- KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");- keyStore.load(null);-- // Create or get biometric key- if (!keyStore.containsAlias(KEYSTORE_ALIAS)) {- KeyGenerator keyGenerator = KeyGenerator.getInstance(- KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");-- KeyGenParameterSpec keySpec = new KeyGenParameterSpec.Builder(- KEYSTORE_ALIAS,- KeyProperties.PURPOSE_ENCRYPT | 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- final SecretKey secretKey = (SecretKey) keyStore.getKey(KEYSTORE_ALIAS, null);-- // Create BiometricPrompt- BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder()- .setTitle("Remember AliasVault password")- .setSubtitle("Protect your AliasVault decryption key with your biometrics.")- .setNegativeButtonText("Cancel")- .build();-- BiometricPrompt biometricPrompt = new BiometricPrompt(activity, executor,- new BiometricPrompt.AuthenticationCallback() {- @Override- public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {- try {- // Get the cipher from the result- Cipher cipher = result.getCryptoObject().getCipher();-- // Encrypt the key- byte[] encryptedKey = cipher.doFinal(keyToStore);- byte[] iv = cipher.getIV();-- // Combine IV and encrypted key- ByteBuffer byteBuffer = ByteBuffer.allocate(iv.length + encryptedKey.length);- byteBuffer.put(iv);- byteBuffer.put(encryptedKey);- byte[] combined = byteBuffer.array();-- // Store encrypted key in SharedPreferences- String encryptedKeyB64 = Base64.encodeToString(combined, Base64.DEFAULT);- SharedPreferences prefs = appContext.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 (Exception e) {- Log.e(TAG, "Error storing encryption key", e);- callback.onError(e);- }- }-- @Override- public void onAuthenticationError(int errorCode, CharSequence errString) {- Log.e(TAG, "Authentication error: " + errString);- callback.onError(new Exception("Authentication error: " + errString));- }-- @Override- public void onAuthenticationFailed() {- Log.e(TAG, "Authentication failed");- }- });-- // Initialize cipher for encryption- Cipher 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, new BiometricPrompt.CryptoObject(cipher));-- } catch (Exception e) {- Log.e(TAG, "Error in biometric key storage", e);- callback.onError(e);- }- }-- /**- * Retrieve the encryption key using biometric authentication- */- private void retrieveEncryptionKey(FragmentActivity activity, final String encryptedKeyB64,- final CryptoOperationCallback callback) {- try {- // Set up KeyStore- KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");- keyStore.load(null);-- // Check if key exists- if (!keyStore.containsAlias(KEYSTORE_ALIAS)) {- Log.e(TAG, "Keystore key not found");- createNewEncryptionKey(activity, callback);- return;- }-- // Get the key- final SecretKey secretKey = (SecretKey) keyStore.getKey(KEYSTORE_ALIAS, null);-- // Create BiometricPrompt- BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder()- .setTitle("Unlock Vault")- .setSubtitle("Unlock your protected AliasVault contents")- .setNegativeButtonText("Cancel")- .build();-- BiometricPrompt biometricPrompt = new BiometricPrompt(activity, executor,- new BiometricPrompt.AuthenticationCallback() {- @Override- public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {- try {- // Get the cipher from the result- Cipher cipher = result.getCryptoObject().getCipher();-- // Decode combined data- byte[] combined = Base64.decode(encryptedKeyB64, Base64.DEFAULT);-- // Extract IV and encrypted data- ByteBuffer byteBuffer = ByteBuffer.wrap(combined);-- // GCM typically uses 12 bytes for IV- byte[] iv = new byte[12];- byteBuffer.get(iv);-- // Get remaining bytes as ciphertext- byte[] encryptedBytes = new byte[byteBuffer.remaining()];- byteBuffer.get(encryptedBytes);-- // Decrypt the key- byte[] decryptedKey = cipher.doFinal(encryptedBytes);-- // Cache the key- encryptionKey = decryptedKey;-- Log.d(TAG, "Encryption key retrieved successfully");- callback.onSuccess("Key retrieved successfully");- } catch (Exception e) {- Log.e(TAG, "Error retrieving encryption key", e);- callback.onError(e);- }- }-- @Override- public void onAuthenticationError(int errorCode, CharSequence errString) {- Log.e(TAG, "Authentication error: " + errString);- callback.onError(new Exception("Authentication error: " + errString));- }-- @Override- public void onAuthenticationFailed() {- Log.e(TAG, "Authentication failed");- }- });-- // Initialize cipher for decryption with IV from stored encrypted key- byte[] combined = Base64.decode(encryptedKeyB64, Base64.DEFAULT);- ByteBuffer byteBuffer = ByteBuffer.wrap(combined);- byte[] iv = new byte[12];- byteBuffer.get(iv);-- Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"- + KeyProperties.BLOCK_MODE_GCM + "/"- + KeyProperties.ENCRYPTION_PADDING_NONE);- GCMParameterSpec spec = new GCMParameterSpec(128, iv);- cipher.init(Cipher.DECRYPT_MODE, secretKey, spec);-- // Show biometric prompt- biometricPrompt.authenticate(promptInfo, new BiometricPrompt.CryptoObject(cipher));-- } catch (Exception e) {- Log.e(TAG, "Error in biometric key retrieval", e);- callback.onError(e);- }- }-- /**- * Encrypts data using AES/GCM/NoPadding- */- private String encryptData(String plaintext) throws Exception {- if (encryptionKey == null) {- throw new Exception("Encryption key not available");- }-- // Create cipher- Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");-- // Create secret key from retrieved bytes- SecretKeySpec secretKeySpec = new SecretKeySpec(encryptionKey, "AES");-- // Initialize cipher for encryption- cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);-- // Get IV- byte[] iv = cipher.getIV();-- // Encrypt data- byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));-- // Combine IV and encrypted data- ByteBuffer byteBuffer = ByteBuffer.allocate(iv.length + encryptedBytes.length);- byteBuffer.put(iv);- byteBuffer.put(encryptedBytes);- byte[] combined = byteBuffer.array();-- // Return Base64 encoded combined data- return Base64.encodeToString(combined, Base64.DEFAULT);- }-- /**- * Decrypts data using AES/GCM/NoPadding- */- private String decryptData(String encryptedData) throws Exception {- if (encryptionKey == null) {- throw new Exception("Encryption key not available");- }-- // Decode combined data- byte[] combined = Base64.decode(encryptedData, Base64.DEFAULT);-- // Extract IV and encrypted data- ByteBuffer byteBuffer = ByteBuffer.wrap(combined);-- // GCM typically uses 12 bytes for IV- byte[] iv = new byte[12];- byteBuffer.get(iv);-- // Get remaining bytes as ciphertext- byte[] encryptedBytes = new byte[byteBuffer.remaining()];- byteBuffer.get(encryptedBytes);-- // Create cipher- Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");-- // Create secret key from retrieved bytes- SecretKeySpec secretKeySpec = new SecretKeySpec(encryptionKey, "AES");-- // Create GCM parameter spec with IV- GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, iv);-- // Initialize cipher for decryption- cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmParameterSpec);-- // Decrypt data- byte[] decryptedBytes = cipher.doFinal(encryptedBytes);-- // Return decrypted string- return new String(decryptedBytes, StandardCharsets.UTF_8);- }-- /**- * Save a credential to SharedPreferences with encryption- */- public void saveCredential(FragmentActivity activity, final Credential credential,- final CryptoOperationCallback callback) {- // First ensure we have the encryption key- getEncryptionKey(activity, new CryptoOperationCallback() {- @Override- public void onSuccess(String result) {- try {- Log.d(TAG, "Saving credential for: " + credential.getService());-- // Get current credentials from SharedPreferences- SharedPreferences prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);- String encryptedCredentialsJson = prefs.getString(CREDENTIALS_KEY, null);-- List<Credential> credentials;- if (encryptedCredentialsJson != null) {- // Decrypt and parse existing credentials- String decryptedJson = decryptData(encryptedCredentialsJson);- credentials = parseCredentialsFromJson(decryptedJson);- } else {- // No existing credentials- credentials = new ArrayList<>();- }-- // Add new credential- credentials.add(credential);-- // Convert to JSON- String jsonData = credentialsToJson(credentials);-- // Encrypt- String encryptedJson = encryptData(jsonData);-- // Save encrypted data- prefs.edit().putString(CREDENTIALS_KEY, encryptedJson).apply();-- callback.onSuccess("Credential saved successfully");- } catch (Exception e) {- Log.e(TAG, "Error saving credential", e);- callback.onError(e);- }- }-- @Override- public void onError(Exception e) {- Log.e(TAG, "Failed to get encryption key", e);- callback.onError(e);- }- });- }-- /**- * Get all credentials from SharedPreferences with decryption- */- public void getAllCredentials(FragmentActivity activity, final CryptoOperationCallback callback) {- // First check if credentials exist- SharedPreferences prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);- String encryptedCredentialsJson = prefs.getString(CREDENTIALS_KEY, null);-- if (encryptedCredentialsJson == null) {- // No credentials found, return empty array without triggering biometric authentication- Log.d(TAG, "No credentials found, returning empty array without key retrieval");- callback.onSuccess(new JSONArray().toString());- return;- }-- // Credentials exist, ensure we have the encryption key- getEncryptionKey(activity, new CryptoOperationCallback() {- @Override- public void onSuccess(String result) {- try {- Log.d(TAG, "Retrieving credentials from SharedPreferences");-- // Decrypt credentials- String decryptedJson = decryptData(encryptedCredentialsJson);-- callback.onSuccess(decryptedJson);- } catch (Exception e) {- Log.e(TAG, "Error retrieving credentials", e);- callback.onError(e);- }- }-- @Override- public void onError(Exception e) {- Log.e(TAG, "Failed to get encryption key", e);- callback.onError(e);- }- });- }-- /**- * Clear all credentials from SharedPreferences- */- public void clearAllData() {- Log.d(TAG, "Clearing all credentials from SharedPreferences");- SharedPreferences prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);- prefs.edit()- .remove(CREDENTIALS_KEY)- .remove(ENCRYPTED_KEY_PREF)- .apply();-- // Clear the cached encryption key- encryptionKey = null;-- // Remove the key from Android Keystore if it exists- try {- KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");- keyStore.load(null);-- if (keyStore.containsAlias(KEYSTORE_ALIAS)) {- keyStore.deleteEntry(KEYSTORE_ALIAS);- Log.d(TAG, "Removed encryption key from Android Keystore");- }- } catch (Exception e) {- Log.e(TAG, "Error removing encryption key from Keystore", e);- }- }-- private List<Credential> parseCredentialsFromJson(String json) throws JSONException {- List<Credential> credentials = new ArrayList<>();-- if (json == null || json.isEmpty()) {- return credentials;- }-- JSONArray jsonArray = new JSONArray(json);-- for (int i = 0; i < jsonArray.length(); i++) {- JSONObject jsonObject = jsonArray.getJSONObject(i);- String username = jsonObject.getString("username");- String password = jsonObject.getString("password");- String service = jsonObject.getString("service");-- credentials.add(new Credential(username, password, service));- }-- return credentials;- }-- private String credentialsToJson(List<Credential> credentials) throws JSONException {- JSONArray jsonArray = new JSONArray();-- for (Credential credential : credentials) {- JSONObject jsonObject = new JSONObject();- jsonObject.put("username", credential.getUsername());- jsonObject.put("password", credential.getPassword());- jsonObject.put("service", credential.getService());-- jsonArray.put(jsonObject);- }-- return jsonArray.toString();- }-}diff --git a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/SharedCredentialStore.kt b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/SharedCredentialStore.ktnew file mode 100644index 000000000..85857c402--- /dev/null+++ b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/SharedCredentialStore.kt@@ -0,0 +1,565 @@+package net.aliasvault.app.credentialmanager++import android.content.Context+import android.content.SharedPreferences+import android.security.keystore.KeyGenParameterSpec+import android.security.keystore.KeyProperties+import android.util.Base64+import android.util.Log+import androidx.biometric.BiometricPrompt+import androidx.fragment.app.FragmentActivity+import org.json.JSONArray+import org.json.JSONException+import org.json.JSONObject+import java.nio.ByteBuffer+import java.nio.charset.StandardCharsets+import java.security.KeyStore+import java.security.SecureRandom+import java.util.concurrent.Executor+import java.util.concurrent.Executors+import javax.crypto.Cipher+import javax.crypto.KeyGenerator+import javax.crypto.SecretKey+import javax.crypto.spec.GCMParameterSpec+import javax.crypto.spec.SecretKeySpec++class SharedCredentialStore private constructor(context: Context) {+ private val appContext = context.applicationContext+ private val executor: Executor = Executors.newSingleThreadExecutor()++ // Cache for encryption key during the lifetime of this instance+ private var encryptionKey: ByteArray? = null++ // Interface for operations that need callbacks+ interface CryptoOperationCallback {+ fun onSuccess(result: String)+ fun onError(e: Exception)+ }++ /**+ * Get or create encryption key using biometric authentication+ */+ fun getEncryptionKey(activity: FragmentActivity, callback: CryptoOperationCallback) {+ // If key is already in memory, use it+ encryptionKey?.let {+ Log.d(TAG, "Using cached encryption key")+ callback.onSuccess("Key available")+ return+ }++ // Check if we have a stored key+ val prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)+ val encryptedKeyB64 = prefs.getString(ENCRYPTED_KEY_PREF, null)++ if (encryptedKeyB64 == null) {+ // No key exists, create a new one+ createNewEncryptionKey(activity, callback)+ } else {+ // Key exists, retrieve it with biometric auth+ retrieveEncryptionKey(activity, encryptedKeyB64, callback)+ }+ }++ /**+ * Create a new random encryption key and protect it with biometrics+ */+ private fun createNewEncryptionKey(activity: FragmentActivity, callback: CryptoOperationCallback) {+ try {+ // Generate a random 32-byte key for AES-256+ val secureRandom = SecureRandom()+ val randomKey = ByteArray(32)+ secureRandom.nextBytes(randomKey)++ // Cache the key+ encryptionKey = randomKey++ // Store the key protected by biometric authentication+ storeKeyWithBiometricProtection(activity, randomKey, callback)+ } catch (e: Exception) {+ Log.e(TAG, "Error creating encryption key", e)+ callback.onError(e)+ }+ }++ /**+ * Store the encryption key protected by biometric authentication+ */+ private fun storeKeyWithBiometricProtection(+ activity: FragmentActivity,+ keyToStore: ByteArray,+ callback: CryptoOperationCallback+ ) {+ 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)+ .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("Remember AliasVault password")+ .setSubtitle("Protect your AliasVault decryption key with your biometrics.")+ .setNegativeButtonText("Cancel")+ .build()++ val biometricPrompt = BiometricPrompt(activity, 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(keyToStore)+ 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 = appContext.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 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)++ // Show biometric prompt+ biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))++ } catch (e: Exception) {+ Log.e(TAG, "Error in biometric key storage", e)+ callback.onError(e)+ }+ }++ /**+ * Retrieve the encryption key using biometric authentication+ */+ private fun retrieveEncryptionKey(+ activity: FragmentActivity,+ encryptedKeyB64: String,+ callback: CryptoOperationCallback+ ) {+ try {+ // 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")+ createNewEncryptionKey(activity, callback)+ return+ }++ // Get the key+ val secretKey = keyStore.getKey(KEYSTORE_ALIAS, null) as SecretKey++ // Create BiometricPrompt+ val promptInfo = BiometricPrompt.PromptInfo.Builder()+ .setTitle("Unlock Vault")+ .setSubtitle("Unlock your protected AliasVault contents")+ .setNegativeButtonText("Cancel")+ .build()++ val biometricPrompt = BiometricPrompt(activity, 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)++ // Cache the key+ encryptionKey = decryptedKey++ Log.d(TAG, "Encryption key retrieved successfully")+ callback.onSuccess("Key retrieved successfully")+ } 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)+ }+ }++ /**+ * Encrypts data using AES/GCM/NoPadding+ */+ @Throws(Exception::class)+ private fun encryptData(plaintext: String): String {+ val key = encryptionKey ?: throw Exception("Encryption key not available")++ // Create cipher+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")++ // Create secret key from retrieved bytes+ val secretKeySpec = SecretKeySpec(key, "AES")++ // Initialize cipher for encryption+ cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec)++ // Get IV+ val iv = cipher.iv++ // Encrypt data+ val encryptedBytes = cipher.doFinal(plaintext.toByteArray(StandardCharsets.UTF_8))++ // Combine IV and encrypted data+ val byteBuffer = ByteBuffer.allocate(iv.size + encryptedBytes.size)+ byteBuffer.put(iv)+ byteBuffer.put(encryptedBytes)+ val combined = byteBuffer.array()++ // Return Base64 encoded combined data+ return Base64.encodeToString(combined, Base64.DEFAULT)+ }++ /**+ * Decrypts data using AES/GCM/NoPadding+ */+ @Throws(Exception::class)+ private fun decryptData(encryptedData: String): String {+ val key = encryptionKey ?: throw Exception("Encryption key not available")++ // Decode combined data+ val combined = Base64.decode(encryptedData, 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)++ // Create cipher+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")++ // Create secret key from retrieved bytes+ val secretKeySpec = SecretKeySpec(key, "AES")++ // Create GCM parameter spec with IV+ val gcmParameterSpec = GCMParameterSpec(128, iv)++ // Initialize cipher for decryption+ cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmParameterSpec)++ // Decrypt data+ val decryptedBytes = cipher.doFinal(encryptedBytes)++ // Return decrypted string+ return String(decryptedBytes, StandardCharsets.UTF_8)+ }++ /**+ * Save a credential to SharedPreferences with encryption+ */+ fun saveCredential(+ activity: FragmentActivity,+ credential: Credential,+ callback: CryptoOperationCallback+ ) {+ // First ensure we have the encryption key+ getEncryptionKey(activity, object : CryptoOperationCallback {+ override fun onSuccess(result: String) {+ try {+ Log.d(TAG, "Saving credential for: ${credential.service}")++ // Get current credentials from SharedPreferences+ val prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)+ val encryptedCredentialsJson = prefs.getString(CREDENTIALS_KEY, null)++ val credentials = if (encryptedCredentialsJson != null) {+ // Decrypt and parse existing credentials+ val decryptedJson = decryptData(encryptedCredentialsJson)+ parseCredentialsFromJson(decryptedJson)+ } else {+ // No existing credentials+ mutableListOf()+ }++ // Add new credential+ credentials.add(credential)++ // Convert to JSON+ val jsonData = credentialsToJson(credentials)++ // Encrypt+ val encryptedJson = encryptData(jsonData)++ // Save encrypted data+ prefs.edit().putString(CREDENTIALS_KEY, encryptedJson).apply()++ callback.onSuccess("Credential saved successfully")+ } catch (e: Exception) {+ Log.e(TAG, "Error saving credential", e)+ callback.onError(e)+ }+ }++ override fun onError(e: Exception) {+ Log.e(TAG, "Failed to get encryption key", e)+ callback.onError(e)+ }+ })+ }++ /**+ * Get all credentials from SharedPreferences with decryption+ */+ fun getAllCredentials(activity: FragmentActivity, callback: CryptoOperationCallback) {+ // First check if credentials exist+ val prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)+ val encryptedCredentialsJson = prefs.getString(CREDENTIALS_KEY, null)++ if (encryptedCredentialsJson == null) {+ // No credentials found, return empty array without triggering biometric authentication+ Log.d(TAG, "No credentials found, returning empty array without key retrieval")+ callback.onSuccess(JSONArray().toString())+ return+ }++ // Credentials exist, ensure we have the encryption key+ getEncryptionKey(activity, object : CryptoOperationCallback {+ override fun onSuccess(result: String) {+ try {+ Log.d(TAG, "Retrieving credentials from SharedPreferences")++ // Decrypt credentials+ val decryptedJson = decryptData(encryptedCredentialsJson)++ callback.onSuccess(decryptedJson)+ } catch (e: Exception) {+ Log.e(TAG, "Error retrieving credentials", e)+ callback.onError(e)+ }+ }++ override fun onError(e: Exception) {+ Log.e(TAG, "Failed to get encryption key", e)+ callback.onError(e)+ }+ })+ }++ /**+ * Attempts to get all credentials using only the cached encryption key.+ * Returns false if the key isn't in memory, which signals the caller to authenticate.+ */+ fun tryGetAllCredentialsWithCachedKey(callback: CryptoOperationCallback): Boolean {+ // Check if the encryption key is already in memory+ if (encryptionKey == null) {+ Log.d(TAG, "Encryption key not in memory, authentication required")+ return false+ }++ // Check if credentials exist+ val prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)+ val encryptedCredentialsJson = prefs.getString(CREDENTIALS_KEY, null)++ if (encryptedCredentialsJson == null) {+ // No credentials found, return empty array+ Log.d(TAG, "No credentials found, returning empty array")+ callback.onSuccess(JSONArray().toString())+ return true+ }++ try {+ Log.d(TAG, "Retrieving credentials using cached key")++ // Decrypt credentials directly with cached key+ val decryptedJson = decryptData(encryptedCredentialsJson)++ callback.onSuccess(decryptedJson)+ return true+ } catch (e: Exception) {+ Log.e(TAG, "Error retrieving credentials with cached key", e)+ callback.onError(e)+ return true // Still return true since we attempted with a cached key+ }+ }++ /**+ * Clear all credentials from SharedPreferences+ */+ fun clearAllData() {+ Log.d(TAG, "Clearing all credentials from SharedPreferences")+ val prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)+ prefs.edit()+ .remove(CREDENTIALS_KEY)+ .remove(ENCRYPTED_KEY_PREF)+ .apply()++ // Clear the cached encryption key+ encryptionKey = null++ // Remove the key from Android Keystore if it exists+ try {+ val keyStore = KeyStore.getInstance("AndroidKeyStore")+ keyStore.load(null)++ if (keyStore.containsAlias(KEYSTORE_ALIAS)) {+ keyStore.deleteEntry(KEYSTORE_ALIAS)+ Log.d(TAG, "Removed encryption key from Android Keystore")+ }+ } catch (e: Exception) {+ Log.e(TAG, "Error removing encryption key from Keystore", e)+ }+ }++ @Throws(JSONException::class)+ private fun parseCredentialsFromJson(json: String?): MutableList<Credential> {+ val credentials = mutableListOf<Credential>()++ if (json.isNullOrEmpty()) {+ return credentials+ }++ val jsonArray = JSONArray(json)++ for (i in 0 until jsonArray.length()) {+ val jsonObject = jsonArray.getJSONObject(i)+ val username = jsonObject.getString("username")+ val password = jsonObject.getString("password")+ val service = jsonObject.getString("service")++ credentials.add(Credential(username, password, service))+ }++ return credentials+ }++ @Throws(JSONException::class)+ private fun credentialsToJson(credentials: List<Credential>): String {+ val jsonArray = JSONArray()++ for (credential in credentials) {+ val jsonObject = JSONObject().apply {+ put("username", credential.username)+ put("password", credential.password)+ put("service", credential.service)+ }++ jsonArray.put(jsonObject)+ }++ return jsonArray.toString()+ }++ companion object {+ private const val TAG = "SharedCredentialStore"+ private const val SHARED_PREFS_NAME = "net.aliasvault.credentials"+ private const val CREDENTIALS_KEY = "stored_credentials"+ private const val KEYSTORE_ALIAS = "net.aliasvault.encryption_key"+ private const val ENCRYPTED_KEY_PREF = "encrypted_key"++ @Volatile+ private var instance: SharedCredentialStore? = null++ @JvmStatic+ fun getInstance(context: Context): SharedCredentialStore {+ return instance ?: synchronized(this) {+ instance ?: SharedCredentialStore(context).also { instance = it }+ }+ }+ }+}\ No newline at end of file