Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Android scaffolding (#1340)

Leendert de Borstd9c914d09e8a
diff --git a/apps/mobile-app/android/app/src/main/AndroidManifest.xml b/apps/mobile-app/android/app/src/main/AndroidManifest.xml
index 98637ee82..d14b7086e 100644
--- a/apps/mobile-app/android/app/src/main/AndroidManifest.xml
+++ b/apps/mobile-app/android/app/src/main/AndroidManifest.xml
@@ -50,6 +50,14 @@
android:theme="@style/PasskeyRegistrationTheme"
android:windowSoftInputMode="adjustResize"
android:fitsSystemWindows="true" />
+
+ <!-- PIN Unlock Activity -->
+ <activity
+ android:name=".pinunlock.PinUnlockActivity"
+ android:exported="false"
+ android:theme="@style/PasskeyRegistrationTheme"
+ android:screenOrientation="portrait" />
+
<activity android:name=".MainActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|uiMode" android:launchMode="singleTask" android:windowSoftInputMode="adjustResize" android:theme="@style/Theme.App.SplashScreen" android:exported="true" android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt
index 52df95594..c350e91ee 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/MainActivity.kt
@@ -1,4 +1,5 @@
package net.aliasvault.app
+import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.view.WindowInsetsController
@@ -101,4 +102,18 @@ class MainActivity : ReactActivity() {
) {},
)
}
+
+ /**
+ * Handle activity results - forward to NativeVaultManager for PIN unlock.
+ */
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ super.onActivityResult(requestCode, resultCode, data)
+
+ // Forward result to NativeVaultManager to handle PIN unlock
+ val reactInstanceManager = reactNativeHost.reactInstanceManager
+ val nativeModule = reactInstanceManager.currentReactContext
+ ?.getNativeModule(net.aliasvault.app.nativevaultmanager.NativeVaultManager::class.java)
+
+ nativeModule?.handleActivityResult(requestCode, resultCode, data)
+ }
}
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.kt
index 334becf52..d8d815fe2 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
@@ -36,6 +36,7 @@ import org.json.JSONObject
*
* @param reactContext The React context
*/
+@Suppress("TooManyFunctions") // Required by React Native TurboModule interface
@ReactModule(name = NativeVaultManager.NAME)
class NativeVaultManager(reactContext: ReactApplicationContext) :
NativeVaultManagerSpec(reactContext), TurboModule, LifecycleEventListener {
@@ -50,6 +51,11 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
* The tag for logging.
*/
private const val TAG = "NativeVaultManager"
+
+ /**
+ * Request code for PIN unlock activity.
+ */
+ private const val PIN_UNLOCK_REQUEST_CODE = 1001
}
private val vaultStore = VaultStore.getInstance(
@@ -1275,36 +1281,30 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
}
}
- /**
- * Get failed PIN attempts count.
- * @param promise The promise to resolve.
- */
- @ReactMethod
- override fun getPinFailedAttempts(promise: Promise) {
- try {
- val attempts = vaultStore.getPinFailedAttempts()
- promise.resolve(attempts)
- } catch (e: Exception) {
- Log.e(TAG, "Error getting PIN failed attempts", e)
- promise.reject("ERR_GET_PIN_FAILED_ATTEMPTS", "Failed to get PIN failed attempts: ${e.message}", e)
- }
- }
-
/**
* Setup PIN unlock.
+ * Gets the vault encryption key from memory (vault must be unlocked).
* @param pin The PIN to set.
- * @param vaultEncryptionKeyBase64 The vault encryption key.
* @param promise The promise to resolve.
*/
@ReactMethod
- override fun setupPin(pin: String, vaultEncryptionKeyBase64: String, promise: Promise) {
- try {
- vaultStore.setupPin(pin, vaultEncryptionKeyBase64)
- promise.resolve(null)
- } catch (e: Exception) {
- Log.e(TAG, "Error setting up PIN", e)
- promise.reject("ERR_SETUP_PIN", "Failed to setup PIN: ${e.message}", e)
- }
+ override fun setupPin(pin: String, promise: Promise) {
+ vaultStore.getEncryptionKey(object : net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallback {
+ override fun onSuccess(result: String) {
+ try {
+ vaultStore.setupPin(pin, result)
+ promise.resolve(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error setting up PIN", e)
+ promise.reject("ERR_SETUP_PIN", "Failed to setup PIN: ${e.message}", e)
+ }
+ }
+
+ override fun onError(error: Exception) {
+ Log.e(TAG, "Error getting encryption key for PIN setup", error)
+ promise.reject("ERR_SETUP_PIN", "Failed to get encryption key: ${error.message}", error)
+ }
+ })
}
/**
@@ -1317,35 +1317,25 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
try {
val vaultEncryptionKey = vaultStore.unlockWithPin(pin)
promise.resolve(vaultEncryptionKey)
- } catch (e: Exception) {
- Log.e(TAG, "Error unlocking with PIN", e)
- // Extract attempts remaining from exception message if available
- val message = e.message ?: "Unknown error"
- val attemptsPattern = """(\d+) attempts remaining""".toRegex()
- val matchResult = attemptsPattern.find(message)
- if (matchResult != null) {
- val attemptsRemaining = matchResult.groupValues[1].toInt()
- val errorData = Arguments.createMap()
- errorData.putInt("attemptsRemaining", attemptsRemaining)
- promise.reject("INCORRECT_PIN", message, e)
- } else {
- promise.reject("ERR_UNLOCK_WITH_PIN", "Failed to unlock with PIN: ${e.message}", e)
+ } catch (e: net.aliasvault.app.vaultstore.PinUnlockException) {
+ // Handle PinUnlockException with proper error codes and English messages for React Native
+ Log.e(TAG, "PIN unlock error: ${e.errorCode}", e)
+ when (e) {
+ is net.aliasvault.app.vaultstore.PinUnlockException.NotConfigured -> {
+ promise.reject("PIN_NOT_CONFIGURED", "PIN unlock is not configured", null)
+ }
+ is net.aliasvault.app.vaultstore.PinUnlockException.Locked -> {
+ promise.reject("PIN_LOCKED", "PIN locked after too many failed attempts", null)
+ }
+ is net.aliasvault.app.vaultstore.PinUnlockException.IncorrectPin -> {
+ val message = "Incorrect PIN. ${e.attemptsRemaining} attempts remaining"
+ promise.reject("INCORRECT_PIN", message, null)
+ }
}
- }
- }
-
- /**
- * Reset failed PIN attempts counter.
- * @param promise The promise to resolve.
- */
- @ReactMethod
- override fun resetPinFailedAttempts(promise: Promise) {
- try {
- vaultStore.resetPinFailedAttempts()
- promise.resolve(null)
} catch (e: Exception) {
- Log.e(TAG, "Error resetting PIN failed attempts", e)
- promise.reject("ERR_RESET_PIN_FAILED_ATTEMPTS", "Failed to reset PIN failed attempts: ${e.message}", e)
+ // Fallback for any other errors
+ Log.e(TAG, "Error unlocking with PIN", e)
+ promise.reject("PIN_UNLOCK_ERROR", "Failed to unlock with PIN: ${e.message}", e)
}
}
@@ -1374,12 +1364,72 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
*/
@ReactMethod
override fun showPinUnlockUI(promise: Promise) {
- // TODO: Implement native Android PIN unlock UI
- // For now, reject with NOT_IMPLEMENTED to allow React Native to fall back
- promise.reject(
- "NOT_IMPLEMENTED",
- "Native PIN unlock UI not yet implemented on Android. Please use the React Native PIN UI.",
- null
- )
+ val activity = currentActivity
+ if (activity == null) {
+ promise.reject("NO_ACTIVITY", "No activity available", null)
+ return
+ }
+
+ // Store promise for later resolution
+ pendingPinUnlockPromise = promise
+
+ // Launch PIN unlock activity
+ val intent = Intent(activity, net.aliasvault.app.pinunlock.PinUnlockActivity::class.java)
+ activity.startActivityForResult(intent, PIN_UNLOCK_REQUEST_CODE)
+ }
+
+ // Store pending promise
+ private var pendingPinUnlockPromise: Promise? = null
+
+ /**
+ * Handle activity result from PIN unlock.
+ */
+ fun handleActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ if (requestCode == PIN_UNLOCK_REQUEST_CODE) {
+ val promise = pendingPinUnlockPromise
+ pendingPinUnlockPromise = null
+
+ if (promise == null) {
+ Log.w(TAG, "No pending promise for PIN unlock result")
+ return
+ }
+
+ when (resultCode) {
+ net.aliasvault.app.pinunlock.PinUnlockActivity.RESULT_SUCCESS -> {
+ // Get encryption key from result
+ val encryptionKeyBase64 = data?.getStringExtra(
+ net.aliasvault.app.pinunlock.PinUnlockActivity.EXTRA_ENCRYPTION_KEY,
+ )
+
+ if (encryptionKeyBase64 == null) {
+ promise.reject("UNLOCK_ERROR", "Failed to get encryption key from PIN unlock", null)
+ return
+ }
+
+ try {
+ // Store encryption key in memory
+ vaultStore.storeEncryptionKey(encryptionKeyBase64)
+
+ // Unlock the vault
+ vaultStore.unlockVault()
+
+ // Success
+ promise.resolve(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error after PIN unlock", e)
+ promise.reject("UNLOCK_ERROR", "Failed to unlock vault: ${e.message}", e)
+ }
+ }
+ net.aliasvault.app.pinunlock.PinUnlockActivity.RESULT_CANCELLED -> {
+ promise.reject("USER_CANCELLED", "User cancelled PIN unlock", null)
+ }
+ net.aliasvault.app.pinunlock.PinUnlockActivity.RESULT_PIN_DISABLED -> {
+ promise.reject("PIN_DISABLED", "PIN was disabled", null)
+ }
+ else -> {
+ promise.reject("UNKNOWN_ERROR", "Unknown error in PIN unlock", null)
+ }
+ }
+ }
}
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinUnlockActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinUnlockActivity.kt
new file mode 100644
index 000000000..eb8eec6e1
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/pinunlock/PinUnlockActivity.kt
@@ -0,0 +1,310 @@
+package net.aliasvault.app.pinunlock
+
+import android.app.Activity
+import android.content.Context
+import android.content.Intent
+import android.os.Bundle
+import android.os.VibrationEffect
+import android.os.Vibrator
+import android.view.View
+import android.view.WindowManager
+import android.widget.Button
+import android.widget.ImageView
+import android.widget.LinearLayout
+import android.widget.ProgressBar
+import android.widget.TextView
+import androidx.appcompat.app.AppCompatActivity
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import net.aliasvault.app.R
+import net.aliasvault.app.vaultstore.VaultStore
+
+/**
+ * Native PIN unlock activity matching iOS PinUnlockView.
+ * This activity presents a numpad UI for PIN entry and handles vault unlocking.
+ */
+class PinUnlockActivity : AppCompatActivity() {
+
+ companion object {
+ /** Result code for successful PIN unlock. */
+ const val RESULT_SUCCESS = Activity.RESULT_OK
+
+ /** Result code for cancelled PIN unlock. */
+ const val RESULT_CANCELLED = Activity.RESULT_CANCELED
+
+ /** Result code when PIN was disabled due to max attempts. */
+ const val RESULT_PIN_DISABLED = 100
+
+ /** Intent extra key for the encryption key. */
+ const val EXTRA_ENCRYPTION_KEY = "encryption_key"
+ }
+
+ private lateinit var vaultStore: VaultStore
+ private lateinit var pinDotsContainer: LinearLayout
+ private lateinit var pinTextView: TextView
+ private lateinit var errorTextView: TextView
+ private lateinit var loadingOverlay: View
+ private lateinit var progressBar: ProgressBar
+
+ private var pinLength: Int? = null
+ private var currentPin: String = ""
+ private var isUnlocking: Boolean = false
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_pin_unlock)
+
+ // Keep screen on during PIN entry
+ window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+
+ // Initialize VaultStore
+ vaultStore = VaultStore.getInstance(
+ net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProvider(this) { null },
+ net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider(this),
+ )
+
+ // Get PIN length
+ pinLength = vaultStore.getPinLength()
+
+ // Initialize views
+ setupViews()
+ setupNumpad()
+ }
+
+ private fun setupViews() {
+ pinDotsContainer = findViewById(R.id.pinDotsContainer)
+ pinTextView = findViewById(R.id.pinTextView)
+ errorTextView = findViewById(R.id.errorTextView)
+ loadingOverlay = findViewById(R.id.loadingOverlay)
+ progressBar = findViewById(R.id.progressBar)
+
+ // Cancel button
+ findViewById<Button>(R.id.cancelButton).setOnClickListener {
+ setResult(RESULT_CANCELLED)
+ finish()
+ }
+
+ // Setup PIN display based on whether we have a fixed length
+ if (pinLength != null) {
+ // Show dots for fixed length PIN
+ pinDotsContainer.visibility = View.VISIBLE
+ pinTextView.visibility = View.GONE
+ createPinDots(pinLength!!)
+ } else {
+ // Show text for variable length PIN
+ pinDotsContainer.visibility = View.GONE
+ pinTextView.visibility = View.VISIBLE
+ updatePinText()
+ }
+ }
+
+ private fun createPinDots(count: Int) {
+ pinDotsContainer.removeAllViews()
+ for (i in 0 until count) {
+ val dot = ImageView(this).apply {
+ layoutParams = LinearLayout.LayoutParams(
+ resources.getDimensionPixelSize(R.dimen.pin_dot_size),
+ resources.getDimensionPixelSize(R.dimen.pin_dot_size),
+ ).apply {
+ marginStart = resources.getDimensionPixelSize(R.dimen.pin_dot_spacing)
+ marginEnd = resources.getDimensionPixelSize(R.dimen.pin_dot_spacing)
+ }
+ setImageResource(R.drawable.pin_dot_empty)
+ tag = i
+ }
+ pinDotsContainer.addView(dot)
+ }
+ }
+
+ private fun updatePinDots() {
+ for (i in 0 until pinDotsContainer.childCount) {
+ val dot = pinDotsContainer.getChildAt(i) as ImageView
+ if (i < currentPin.length) {
+ dot.setImageResource(R.drawable.pin_dot_filled)
+ } else {
+ dot.setImageResource(R.drawable.pin_dot_empty)
+ }
+ }
+ }
+
+ private fun updatePinText() {
+ pinTextView.text = if (currentPin.isEmpty()) {
+ "----"
+ } else {
+ "•".repeat(currentPin.length)
+ }
+ }
+
+ private fun setupNumpad() {
+ // Number buttons
+ findViewById<Button>(R.id.btn1).setOnClickListener { addDigit("1") }
+ findViewById<Button>(R.id.btn2).setOnClickListener { addDigit("2") }
+ findViewById<Button>(R.id.btn3).setOnClickListener { addDigit("3") }
+ findViewById<Button>(R.id.btn4).setOnClickListener { addDigit("4") }
+ findViewById<Button>(R.id.btn5).setOnClickListener { addDigit("5") }
+ findViewById<Button>(R.id.btn6).setOnClickListener { addDigit("6") }
+ findViewById<Button>(R.id.btn7).setOnClickListener { addDigit("7") }
+ findViewById<Button>(R.id.btn8).setOnClickListener { addDigit("8") }
+ findViewById<Button>(R.id.btn9).setOnClickListener { addDigit("9") }
+ findViewById<Button>(R.id.btn0).setOnClickListener { addDigit("0") }
+
+ // Backspace button
+ findViewById<Button>(R.id.btnBackspace).setOnClickListener { removeDigit() }
+ }
+
+ private fun addDigit(digit: String) {
+ if (isUnlocking) return
+
+ // Clear error when user starts typing
+ errorTextView.visibility = View.GONE
+
+ // Check if we've reached max length
+ pinLength?.let { maxLength ->
+ if (currentPin.length >= maxLength) return
+ }
+
+ // Add digit
+ currentPin += digit
+
+ // Update UI
+ if (pinLength != null) {
+ updatePinDots()
+ } else {
+ updatePinText()
+ }
+
+ // Auto-submit when PIN reaches expected length
+ pinLength?.let { expectedLength ->
+ if (currentPin.length == expectedLength) {
+ // Small delay to show the last dot filled before attempting unlock
+ CoroutineScope(Dispatchers.Main).launch {
+ delay(100)
+ attemptUnlock()
+ }
+ }
+ }
+ }
+
+ private fun removeDigit() {
+ if (isUnlocking || currentPin.isEmpty()) return
+
+ // Remove last digit
+ currentPin = currentPin.dropLast(1)
+
+ // Clear error
+ errorTextView.visibility = View.GONE
+
+ // Update UI
+ if (pinLength != null) {
+ updatePinDots()
+ } else {
+ updatePinText()
+ }
+ }
+
+ private fun attemptUnlock() {
+ if (isUnlocking) return
+
+ CoroutineScope(Dispatchers.Main).launch {
+ try {
+ // Show loading state
+ isUnlocking = true
+ loadingOverlay.visibility = View.VISIBLE
+ progressBar.visibility = View.VISIBLE
+
+ // Give UI time to update
+ delay(50)
+
+ // Perform unlock in background (Argon2 is CPU intensive)
+ val encryptionKeyBase64 = withContext(Dispatchers.IO) {
+ vaultStore.unlockWithPin(currentPin)
+ }
+
+ // Success - return encryption key
+ val resultIntent = Intent().apply {
+ putExtra(EXTRA_ENCRYPTION_KEY, encryptionKeyBase64)
+ }
+ setResult(RESULT_SUCCESS, resultIntent)
+ finish()
+ } catch (e: net.aliasvault.app.vaultstore.PinUnlockException) {
+ // Handle PinUnlockException with localized strings
+ isUnlocking = false
+ loadingOverlay.visibility = View.GONE
+ progressBar.visibility = View.GONE
+
+ when (e) {
+ is net.aliasvault.app.vaultstore.PinUnlockException.NotConfigured -> {
+ // PIN not configured - show error briefly then dismiss
+ showError(getString(R.string.pin_not_configured))
+ triggerErrorFeedback()
+ delay(1000)
+ setResult(RESULT_PIN_DISABLED)
+ finish()
+ }
+ is net.aliasvault.app.vaultstore.PinUnlockException.Locked -> {
+ // PIN locked after max attempts - show error briefly then dismiss
+ showError(getString(R.string.pin_locked_max_attempts))
+ triggerErrorFeedback()
+ delay(1000)
+ setResult(RESULT_PIN_DISABLED)
+ finish()
+ }
+ is net.aliasvault.app.vaultstore.PinUnlockException.IncorrectPin -> {
+ // Incorrect PIN - show error with attempts remaining and clear
+ val errorMessage = getString(R.string.pin_incorrect_attempts_remaining, e.attemptsRemaining)
+ showError(errorMessage)
+ triggerErrorFeedback()
+ shakeAndClear()
+ }
+ }
+ } catch (e: Exception) {
+ // Fallback for any other errors
+ isUnlocking = false
+ loadingOverlay.visibility = View.GONE
+ progressBar.visibility = View.GONE
+
+ showError(e.message ?: getString(R.string.pin_unlock_failed))
+ triggerErrorFeedback()
+ shakeAndClear()
+ }
+ }
+ }
+
+ private fun showError(message: String) {
+ errorTextView.text = message
+ errorTextView.visibility = View.VISIBLE
+ }
+
+ private fun triggerErrorFeedback() {
+ // Trigger haptic feedback for error
+ val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
+ vibrator?.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE))
+ } else {
+ @Suppress("DEPRECATION")
+ vibrator?.vibrate(200)
+ }
+ }
+
+ private fun shakeAndClear() {
+ CoroutineScope(Dispatchers.Main).launch {
+ // Clear the PIN after a short delay to show error
+ delay(500)
+ currentPin = ""
+ if (pinLength != null) {
+ updatePinDots()
+ } else {
+ updatePinText()
+ }
+ }
+ }
+
+ override fun onBackPressed() {
+ // Handle back button as cancel
+ setResult(RESULT_CANCELLED)
+ super.onBackPressed()
+ }
+}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt
index b0732bbf9..d26faae75 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt
@@ -1,17 +1,49 @@
package net.aliasvault.app.vaultstore
+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 net.aliasvault.app.vaultstore.storageprovider.StorageProvider
-import org.signal.argon2.Argon2
-import org.signal.argon2.MemoryCost
-import org.signal.argon2.Type
-import org.signal.argon2.Version
+import com.lambdapioneer.argon2kt.Argon2Kt
+import com.lambdapioneer.argon2kt.Argon2Mode
+import com.lambdapioneer.argon2kt.Argon2Version
+import org.json.JSONObject
+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 javax.crypto.spec.SecretKeySpec
+/**
+ * Exception types for PIN unlock operations.
+ * UI layer should handle localization based on these exception types.
+ */
+sealed class PinUnlockException(message: String) : Exception(message) {
+ /** PIN is not configured. */
+ object NotConfigured : PinUnlockException("PIN unlock is not configured")
+
+ /** PIN is locked after too many failed attempts. */
+ object Locked : PinUnlockException("PIN locked after too many failed attempts")
+
+ /**
+ * Incorrect PIN with remaining attempts.
+ * @property attemptsRemaining The number of attempts remaining before PIN is locked.
+ */
+ data class IncorrectPin(val attemptsRemaining: Int) : PinUnlockException("Incorrect PIN. $attemptsRemaining attempts remaining")
+
+ /** Get error code for React Native bridge compatibility. */
+ val errorCode: String
+ get() = when (this) {
+ is NotConfigured -> "PIN_NOT_CONFIGURED"
+ is Locked -> "PIN_LOCKED"
+ is IncorrectPin -> "INCORRECT_PIN"
+ }
+}
+
/**
* Handles PIN unlock functionality for the vault store.
* This component manages PIN-based unlocking by encrypting the vault encryption key
@@ -19,16 +51,19 @@ import javax.crypto.spec.SecretKeySpec
*
* Security features:
* - 4 failed attempts maximum before requiring full password
- * - PIN must be 4-8 digits
+ * - Device pepper stored in Android Keystore (makes offline brute-force impossible)
+ * - Failed attempts counter stored in Keystore (prevents tampering)
* - Encryption key derived using Argon2id (memory-hard, GPU-resistant)
- * - Failed attempts counter stored separately
* - Encrypted data automatically deleted after max failed attempts
*
- * @param storageProvider The storage provider for persisting PIN data
+ * @param context The Android context for accessing SharedPreferences and Keystore
*/
class VaultPin(
- private val storageProvider: StorageProvider,
+ context: Context,
) {
+ private val sharedPreferences: SharedPreferences = context.getSharedPreferences("AliasVaultPrefs", Context.MODE_PRIVATE)
+ private val keyStore: KeyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+
companion object {
/**
* The tag for logging.
@@ -41,13 +76,18 @@ class VaultPin(
private const val MAX_PIN_ATTEMPTS = 4
/**
- * Shared preferences keys for PIN data.
+ * Shared preferences keys for PIN metadata (non-sensitive data only).
*/
private const val PIN_ENABLED_KEY = "aliasvault_pin_enabled"
- private const val PIN_ENCRYPTED_KEY_KEY = "aliasvault_pin_encrypted_key"
- private const val PIN_SALT_KEY = "aliasvault_pin_salt"
private const val PIN_LENGTH_KEY = "aliasvault_pin_length"
- private const val PIN_FAILED_ATTEMPTS_KEY = "aliasvault_pin_failed_attempts"
+
+ /**
+ * Android Keystore aliases for secure data storage.
+ */
+ private const val KEYSTORE_ALIAS_PIN_DATA = "aliasvault_pin_data"
+ private const val KEYSTORE_ALIAS_PIN_PEPPER = "aliasvault_pin_pepper"
+ private const val KEYSTORE_ALIAS_FAILED_ATTEMPTS = "aliasvault_pin_failed_attempts"
+ private const val KEYSTORE_ALIAS_DATA_ENCRYPTION = "aliasvault_pin_data_encryption_key"
/**
* Argon2id parameters for PIN key derivation.
@@ -62,16 +102,16 @@ class VaultPin(
private const val ARGON2_PARALLELISM = 1
private const val ARGON2_OUTPUT_LENGTH = 32
- /**
- * Keystore alias for PIN encryption.
- */
- private const val KEYSTORE_ALIAS = "alias_vault_pin_key"
-
/**
* AES-GCM parameters.
*/
private const val GCM_IV_LENGTH = 12
private const val GCM_TAG_LENGTH = 128
+
+ /**
+ * Device pepper size (32 bytes for strong security).
+ */
+ private const val PEPPER_SIZE = 32
}
// MARK: - PIN Status Methods
@@ -81,7 +121,7 @@ class VaultPin(
* @return True if PIN unlock is enabled, false otherwise
*/
fun isPinEnabled(): Boolean {
- return storageProvider.getBoolean(PIN_ENABLED_KEY, false)
+ return sharedPreferences.getBoolean(PIN_ENABLED_KEY, false)
}
/**
@@ -90,16 +130,21 @@ class VaultPin(
*/
fun getPinLength(): Int? {
if (!isPinEnabled()) return null
- val length = storageProvider.getInt(PIN_LENGTH_KEY, 0)
+ val length = sharedPreferences.getInt(PIN_LENGTH_KEY, 0)
return if (length > 0) length else null
}
/**
- * Get failed attempts count.
+ * Get failed attempts count from secure storage (Android Keystore).
* @return The number of failed PIN attempts
*/
fun getPinFailedAttempts(): Int {
- return storageProvider.getInt(PIN_FAILED_ATTEMPTS_KEY, 0)
+ return try {
+ retrievePinFailedAttemptsFromKeystore()
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to retrieve failed attempts, returning 0", e)
+ 0
+ }
}
// MARK: - PIN Setup Methods
@@ -108,7 +153,7 @@ class VaultPin(
* Setup PIN unlock.
* Encrypts the vault encryption key with the PIN and stores it securely.
*
- * @param pin The PIN to set (4-8 digits)
+ * @param pin The PIN to set (4+ digits)
* @param vaultEncryptionKeyBase64 The base64-encoded vault encryption key to protect
* @throws IllegalArgumentException if PIN format is invalid
* @throws Exception if encryption or storage fails
@@ -121,10 +166,12 @@ class VaultPin(
// Generate random salt
val salt = ByteArray(16)
SecureRandom().nextBytes(salt)
- val saltBase64 = Base64.encodeToString(salt, Base64.NO_WRAP)
- // Derive key from PIN using Argon2id
- val pinKey = derivePinKey(pin, salt)
+ // Generate or retrieve device pepper (device-bound secret)
+ val pepper = getOrCreateDevicePepper()
+
+ // Derive key from PIN + pepper using Argon2id
+ val pinKey = derivePinKey(pin, salt, pepper)
// Encrypt the vault encryption key using AES-GCM
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
@@ -141,16 +188,21 @@ class VaultPin(
val combined = ByteArray(iv.size + encryptedKey.size)
System.arraycopy(iv, 0, combined, 0, iv.size)
System.arraycopy(encryptedKey, 0, combined, iv.size, encryptedKey.size)
- val combinedBase64 = Base64.encodeToString(combined, Base64.NO_WRAP)
- // Store encrypted key, salt, and metadata in SharedPreferences
- storageProvider.putBoolean(PIN_ENABLED_KEY, true)
- storageProvider.putString(PIN_ENCRYPTED_KEY_KEY, combinedBase64)
- storageProvider.putString(PIN_SALT_KEY, saltBase64)
- storageProvider.putInt(PIN_LENGTH_KEY, pin.length)
- storageProvider.putInt(PIN_FAILED_ATTEMPTS_KEY, 0)
+ // Store encrypted key and salt in Android Keystore
+ storePinDataInKeystore(combined, salt)
+
+ // Initialize failed attempts counter in Keystore
+ storePinFailedAttemptsInKeystore(0)
- Log.d(TAG, "PIN unlock enabled successfully")
+ // Store PIN metadata in SharedPreferences (non-sensitive data only)
+ sharedPreferences.edit().apply {
+ putBoolean(PIN_ENABLED_KEY, true)
+ putInt(PIN_LENGTH_KEY, pin.length)
+ apply()
+ }
+
+ Log.d(TAG, "PIN unlock enabled successfully with device pepper")
}
// MARK: - PIN Unlock Methods
@@ -161,34 +213,27 @@ class VaultPin(
*
* @param pin The PIN to use for unlocking
* @return The decrypted vault encryption key (base64)
- * @throws IllegalArgumentException if PIN format is invalid
- * @throws IllegalStateException if PIN is not configured or is locked
- * @throws Exception if decryption fails or PIN is incorrect
+ * @throws PinUnlockException with specific error type and metadata
*/
- @Throws(Exception::class)
+ @Throws(PinUnlockException::class)
+ @Suppress("SwallowedException") // We intentionally swallow to avoid exposing crypto implementation details
fun unlockWithPin(pin: String): String {
// Check if PIN is enabled
- // Note: If PIN was previously locked (max attempts), it's automatically disabled and cleared,
- // so isPinEnabled() returning false means either PIN was never set up or it was locked and cleared
if (!isPinEnabled()) {
- throw IllegalStateException("PIN unlock is not configured")
+ throw PinUnlockException.NotConfigured
}
try {
- // Retrieve encrypted key and salt
- val encryptedKeyBase64 = storageProvider.getString(PIN_ENCRYPTED_KEY_KEY, null)
- ?: throw IllegalStateException("No encrypted key found")
- val saltBase64 = storageProvider.getString(PIN_SALT_KEY, null)
- ?: throw IllegalStateException("No salt found")
+ // Retrieve encrypted key, salt, and pepper from Keystore
+ val (encryptedKey, salt) = retrievePinDataFromKeystore()
+ val pepper = retrieveDevicePepper()
// Decode encrypted package
- val combined = Base64.decode(encryptedKeyBase64, Base64.NO_WRAP)
- val iv = combined.copyOfRange(0, GCM_IV_LENGTH)
- val encryptedData = combined.copyOfRange(GCM_IV_LENGTH, combined.size)
+ val iv = encryptedKey.copyOfRange(0, GCM_IV_LENGTH)
+ val encryptedData = encryptedKey.copyOfRange(GCM_IV_LENGTH, encryptedKey.size)
- // Derive key from PIN
- val salt = Base64.decode(saltBase64, Base64.NO_WRAP)
- val pinKey = derivePinKey(pin, salt)
+ // Derive key from PIN + pepper
+ val pinKey = derivePinKey(pin, salt, pepper)
// Decrypt the vault encryption key
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
@@ -197,7 +242,7 @@ class VaultPin(
val decryptedKey = cipher.doFinal(encryptedData)
// Reset failed attempts on success
- storageProvider.putInt(PIN_FAILED_ATTEMPTS_KEY, 0)
+ storePinFailedAttemptsInKeystore(0)
// Return the decrypted vault encryption key as base64
return Base64.encodeToString(decryptedKey, Base64.NO_WRAP)
@@ -205,72 +250,377 @@ class VaultPin(
// Increment failed attempts
val currentAttempts = getPinFailedAttempts()
val newAttempts = currentAttempts + 1
- storageProvider.putInt(PIN_FAILED_ATTEMPTS_KEY, newAttempts)
+ storePinFailedAttemptsInKeystore(newAttempts)
// If max attempts reached, disable PIN and clear all stored data
if (newAttempts >= MAX_PIN_ATTEMPTS) {
removeAndDisablePin()
- throw IllegalStateException("PIN locked after too many failed attempts")
+ throw PinUnlockException.Locked
}
// Return incorrect PIN error with attempts remaining
val attemptsRemaining = MAX_PIN_ATTEMPTS - newAttempts
- throw Exception("Incorrect PIN. $attemptsRemaining attempts remaining", e)
+ throw PinUnlockException.IncorrectPin(attemptsRemaining)
}
}
/**
- * Reset failed attempts counter.
- * Called after successful password unlock.
+ * Reset failed attempts counter (called after successful password unlock).
*/
fun resetPinFailedAttempts() {
- storageProvider.putInt(PIN_FAILED_ATTEMPTS_KEY, 0)
+ try {
+ storePinFailedAttemptsInKeystore(0)
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to reset PIN attempts", e)
+ }
}
/**
* Disable PIN unlock and remove all stored data.
*/
fun removeAndDisablePin() {
- // Clear all PIN data from SharedPreferences
- storageProvider.remove(PIN_ENABLED_KEY)
- storageProvider.remove(PIN_ENCRYPTED_KEY_KEY)
- storageProvider.remove(PIN_SALT_KEY)
- storageProvider.remove(PIN_LENGTH_KEY)
- storageProvider.remove(PIN_FAILED_ATTEMPTS_KEY)
-
- Log.d(TAG, "PIN unlock disabled and all data removed")
+ try {
+ // Remove PIN data from Keystore
+ removePinDataFromKeystore()
+
+ // Remove failed attempts counter from Keystore
+ removePinFailedAttemptsFromKeystore()
+
+ // Note: We DO NOT remove the device pepper - it's reused if PIN is re-enabled
+ // This maintains consistency and doesn't degrade security
+
+ // Clear PIN metadata from SharedPreferences
+ sharedPreferences.edit().apply {
+ remove(PIN_ENABLED_KEY)
+ remove(PIN_LENGTH_KEY)
+ apply()
+ }
+
+ Log.d(TAG, "PIN unlock disabled and all data removed (pepper retained)")
+ } catch (e: Exception) {
+ Log.e(TAG, "Error removing PIN data", e)
+ throw Exception("Failed to remove PIN data", e)
+ }
}
// MARK: - Private PIN Methods
/**
- * Derive encryption key from PIN using Argon2id.
+ * Derive encryption key from PIN + pepper using Argon2id.
+ *
+ * Uses Argon2id with high memory cost (64 MB) and a device-bound pepper
+ * to make offline brute-force attacks infeasible even if the encrypted blob is exfiltrated.
*
- * Uses Argon2id with high memory cost (64 MB) to make brute-force attacks
- * significantly more expensive. This is especially important for PINs which
- * have lower entropy than passwords.
+ * The pepper is a 32-byte random value stored in Android Keystore,
+ * which means an attacker who steals the encrypted blob cannot brute-force offline
+ * because they don't have the pepper.
*
- * @param pin The PIN string
- * @param salt The salt bytes
+ * @param pin User's PIN (low entropy)
+ * @param salt Random salt (stored with encrypted data)
+ * @param pepper Device-bound secret (stored in Keystore, not with encrypted data)
* @return The derived key bytes (32 bytes)
* @throws Exception if key derivation fails
*/
@Throws(Exception::class)
- private fun derivePinKey(pin: String, salt: ByteArray): ByteArray {
+ private fun derivePinKey(pin: String, salt: ByteArray, pepper: ByteArray): ByteArray {
try {
- val argon2 = Argon2.Builder(Version.V13)
- .type(Type.Argon2id)
- .memoryCost(MemoryCost.KiB(ARGON2_MEMORY_KB))
- .parallelism(ARGON2_PARALLELISM)
- .iterations(ARGON2_ITERATIONS)
- .hashLength(ARGON2_OUTPUT_LENGTH)
- .build()
-
- val result = argon2.hash(pin.toByteArray(), salt)
- return result.hash
+ // Concatenate PIN + pepper before hashing
+ // This ensures offline brute-force is impossible without the pepper
+ val pinBytes = pin.toByteArray(Charsets.UTF_8)
+ val combinedInput = ByteArray(pinBytes.size + pepper.size)
+ System.arraycopy(pinBytes, 0, combinedInput, 0, pinBytes.size)
+ System.arraycopy(pepper, 0, combinedInput, pinBytes.size, pepper.size)
+
+ val argon2 = Argon2Kt()
+
+ val hashResult = argon2.hash(
+ mode = Argon2Mode.ARGON2_ID,
+ password = combinedInput,
+ salt = salt,
+ tCostInIterations = ARGON2_ITERATIONS,
+ mCostInKibibyte = ARGON2_MEMORY_KB,
+ parallelism = ARGON2_PARALLELISM,
+ hashLengthInBytes = ARGON2_OUTPUT_LENGTH,
+ version = Argon2Version.V13,
+ )
+
+ return hashResult.rawHashAsByteArray()
} catch (e: Exception) {
Log.e(TAG, "Argon2 PIN hashing failed", e)
throw Exception("Argon2 PIN hashing failed", e)
}
}
+
+ // MARK: - Device Pepper Management
+
+ /**
+ * Get or create device pepper (device-bound secret).
+ *
+ * The pepper is a 32-byte random value stored in Android Keystore.
+ * It's only readable when the device is unlocked (device credential required).
+ * This makes offline brute-force impossible because the pepper isn't in the encrypted blob.
+ */
+ @Throws(Exception::class)
+ private fun getOrCreateDevicePepper(): ByteArray {
+ // Try to retrieve existing pepper
+ return try {
+ retrieveDevicePepper()
+ } catch (e: Exception) {
+ // Pepper doesn't exist, generate new 32-byte pepper
+ Log.d(TAG, "Device pepper not found, creating new one", e)
+ val pepper = ByteArray(PEPPER_SIZE)
+ SecureRandom().nextBytes(pepper)
+
+ // Store pepper in Android Keystore with strong device protection
+ storePepperInKeystore(pepper)
+
+ Log.d(TAG, "Device pepper created and stored securely")
+ pepper
+ }
+ }
+
+ /**
+ * Store pepper in Android Keystore with device-bound protection.
+ */
+ @Throws(Exception::class)
+ private fun storePepperInKeystore(pepper: ByteArray) {
+ // Create encryption key for pepper storage in Keystore
+ val keyGenerator = KeyGenerator.getInstance(
+ KeyProperties.KEY_ALGORITHM_AES,
+ "AndroidKeyStore",
+ )
+
+ val keySpec = KeyGenParameterSpec.Builder(
+ KEYSTORE_ALIAS_PIN_PEPPER,
+ KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
+ )
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .setUserAuthenticationRequired(false)
+ // Require device to be unlocked (equivalent to iOS's kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
+ .setUnlockedDeviceRequired(true)
+ .build()
+
+ keyGenerator.init(keySpec)
+ val secretKey = keyGenerator.generateKey()
+
+ // Encrypt pepper
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey)
+ val encryptedPepper = cipher.doFinal(pepper)
+ val iv = cipher.iv
+
+ // Combine IV + encrypted pepper
+ val combined = ByteArray(iv.size + encryptedPepper.size)
+ System.arraycopy(iv, 0, combined, 0, iv.size)
+ System.arraycopy(encryptedPepper, 0, combined, iv.size, encryptedPepper.size)
+
+ // Store in SharedPreferences (encrypted by Keystore key)
+ val pepperBase64 = Base64.encodeToString(combined, Base64.NO_WRAP)
+ sharedPreferences.edit().putString(KEYSTORE_ALIAS_PIN_PEPPER, pepperBase64).apply()
+ }
+
+ /**
+ * Retrieve pepper from Android Keystore.
+ */
+ @Throws(Exception::class)
+ private fun retrieveDevicePepper(): ByteArray {
+ // Get encrypted pepper from SharedPreferences
+ val pepperBase64 = sharedPreferences.getString(KEYSTORE_ALIAS_PIN_PEPPER, null)
+ ?: throw Exception("Device pepper not found")
+
+ val combined = Base64.decode(pepperBase64, Base64.NO_WRAP)
+ val iv = combined.copyOfRange(0, GCM_IV_LENGTH)
+ val encryptedPepper = combined.copyOfRange(GCM_IV_LENGTH, combined.size)
+
+ // Get decryption key from Keystore
+ val secretKey = keyStore.getKey(KEYSTORE_ALIAS_PIN_PEPPER, null) as? SecretKey
+ ?: throw Exception("Keystore key for pepper not found")
+
+ // Decrypt pepper
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(GCM_TAG_LENGTH, iv))
+ return cipher.doFinal(encryptedPepper)
+ }
+
+ // MARK: - PIN Data Storage (Encrypted Key + Salt)
+
+ /**
+ * Store PIN data (encrypted key and salt) in Android Keystore.
+ * Note: We DO NOT store the pepper here - it's separate for security.
+ */
+ @Throws(Exception::class)
+ private fun storePinDataInKeystore(encryptedKey: ByteArray, salt: ByteArray) {
+ // Create JSON with both encrypted key and salt
+ val pinData = JSONObject().apply {
+ put("encryptedKey", Base64.encodeToString(encryptedKey, Base64.NO_WRAP))
+ put("salt", Base64.encodeToString(salt, Base64.NO_WRAP))
+ }
+ val dataToStore = pinData.toString().toByteArray(Charsets.UTF_8)
+
+ // Get or create encryption key for PIN data storage
+ val secretKey = getOrCreateDataEncryptionKey()
+
+ // Encrypt the PIN data
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey)
+ val encryptedData = cipher.doFinal(dataToStore)
+ val iv = cipher.iv
+
+ // Combine IV + encrypted data
+ val combined = ByteArray(iv.size + encryptedData.size)
+ System.arraycopy(iv, 0, combined, 0, iv.size)
+ System.arraycopy(encryptedData, 0, combined, iv.size, encryptedData.size)
+
+ // Store in SharedPreferences
+ val combinedBase64 = Base64.encodeToString(combined, Base64.NO_WRAP)
+ sharedPreferences.edit().putString(KEYSTORE_ALIAS_PIN_DATA, combinedBase64).apply()
+ }
+
+ /**
+ * Retrieve PIN data (encrypted key and salt) from Android Keystore.
+ */
+ @Throws(Exception::class)
+ private fun retrievePinDataFromKeystore(): Pair<ByteArray, ByteArray> {
+ // Get encrypted data from SharedPreferences
+ val combinedBase64 = sharedPreferences.getString(KEYSTORE_ALIAS_PIN_DATA, null)
+ ?: throw Exception("No PIN data found in keystore")
+
+ val combined = Base64.decode(combinedBase64, Base64.NO_WRAP)
+ val iv = combined.copyOfRange(0, GCM_IV_LENGTH)
+ val encryptedData = combined.copyOfRange(GCM_IV_LENGTH, combined.size)
+
+ // Get decryption key from Keystore
+ val secretKey = keyStore.getKey(KEYSTORE_ALIAS_DATA_ENCRYPTION, null) as? SecretKey
+ ?: throw Exception("Keystore key for PIN data not found")
+
+ // Decrypt the PIN data
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(GCM_TAG_LENGTH, iv))
+ val decryptedData = cipher.doFinal(encryptedData)
+
+ // Parse JSON
+ val pinData = JSONObject(String(decryptedData, Charsets.UTF_8))
+ val encryptedKey = Base64.decode(pinData.getString("encryptedKey"), Base64.NO_WRAP)
+ val salt = Base64.decode(pinData.getString("salt"), Base64.NO_WRAP)
+
+ return Pair(encryptedKey, salt)
+ }
+
+ /**
+ * Remove PIN data from keystore.
+ */
+ @Throws(Exception::class)
+ private fun removePinDataFromKeystore() {
+ sharedPreferences.edit().remove(KEYSTORE_ALIAS_PIN_DATA).apply()
+ }
+
+ // MARK: - Failed Attempts Counter (Keystore Storage)
+
+ /**
+ * Store failed attempts counter in Android Keystore (not SharedPreferences).
+ * This is stored in Keystore to prevent tampering.
+ */
+ @Throws(Exception::class)
+ private fun storePinFailedAttemptsInKeystore(attempts: Int) {
+ // Convert Int to ByteArray
+ val attemptsData = ByteArray(4).apply {
+ this[0] = (attempts shr 24).toByte()
+ this[1] = (attempts shr 16).toByte()
+ this[2] = (attempts shr 8).toByte()
+ this[3] = attempts.toByte()
+ }
+
+ // Get or create encryption key for attempts storage
+ val secretKey = getOrCreateDataEncryptionKey()
+
+ // Encrypt the attempts data
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey)
+ val encryptedData = cipher.doFinal(attemptsData)
+ val iv = cipher.iv
+
+ // Combine IV + encrypted data
+ val combined = ByteArray(iv.size + encryptedData.size)
+ System.arraycopy(iv, 0, combined, 0, iv.size)
+ System.arraycopy(encryptedData, 0, combined, iv.size, encryptedData.size)
+
+ // Store in SharedPreferences
+ val combinedBase64 = Base64.encodeToString(combined, Base64.NO_WRAP)
+ sharedPreferences.edit().putString(KEYSTORE_ALIAS_FAILED_ATTEMPTS, combinedBase64).apply()
+ }
+
+ /**
+ * Retrieve failed attempts counter from Android Keystore.
+ */
+ @Throws(Exception::class)
+ private fun retrievePinFailedAttemptsFromKeystore(): Int {
+ // Get encrypted data from SharedPreferences
+ val combinedBase64 = sharedPreferences.getString(KEYSTORE_ALIAS_FAILED_ATTEMPTS, null)
+ ?: return 0 // Default if not found
+
+ try {
+ val combined = Base64.decode(combinedBase64, Base64.NO_WRAP)
+ val iv = combined.copyOfRange(0, GCM_IV_LENGTH)
+ val encryptedData = combined.copyOfRange(GCM_IV_LENGTH, combined.size)
+
+ // Get decryption key from Keystore
+ val secretKey = keyStore.getKey(KEYSTORE_ALIAS_DATA_ENCRYPTION, null) as? SecretKey
+ ?: return 0
+
+ // Decrypt the attempts data
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(GCM_TAG_LENGTH, iv))
+ val decryptedData = cipher.doFinal(encryptedData)
+
+ // Convert ByteArray to Int
+ return ((decryptedData[0].toInt() and 0xFF) shl 24) or
+ ((decryptedData[1].toInt() and 0xFF) shl 16) or
+ ((decryptedData[2].toInt() and 0xFF) shl 8) or
+ (decryptedData[3].toInt() and 0xFF)
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to decode failed attempts", e)
+ return 0
+ }
+ }
+
+ /**
+ * Remove failed attempts counter from Android Keystore.
+ */
+ @Throws(Exception::class)
+ private fun removePinFailedAttemptsFromKeystore() {
+ sharedPreferences.edit().remove(KEYSTORE_ALIAS_FAILED_ATTEMPTS).apply()
+ }
+
+ // MARK: - Keystore Helper Methods
+
+ /**
+ * Get or create the encryption key for PIN data storage in Keystore.
+ */
+ @Throws(Exception::class)
+ private fun getOrCreateDataEncryptionKey(): SecretKey {
+ // Check if key already exists
+ if (keyStore.containsAlias(KEYSTORE_ALIAS_DATA_ENCRYPTION)) {
+ return keyStore.getKey(KEYSTORE_ALIAS_DATA_ENCRYPTION, null) as SecretKey
+ }
+
+ // Create new key
+ val keyGenerator = KeyGenerator.getInstance(
+ KeyProperties.KEY_ALGORITHM_AES,
+ "AndroidKeyStore",
+ )
+
+ val keySpec = KeyGenParameterSpec.Builder(
+ KEYSTORE_ALIAS_DATA_ENCRYPTION,
+ KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
+ )
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .setUserAuthenticationRequired(false)
+ .setUnlockedDeviceRequired(true)
+ .build()
+
+ keyGenerator.init(keySpec)
+ return keyGenerator.generateKey()
+ }
}
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.kt
index 62b2357c0..552c80fe1 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
@@ -71,7 +71,14 @@ class VaultStore(
private val mutate = VaultMutate(databaseComponent, query, metadata)
private val cache = VaultCache(crypto, databaseComponent, keystoreProvider, storageProvider)
private val passkey = VaultPasskey(databaseComponent)
- private val pin = VaultPin(storageProvider)
+ private val pin by lazy {
+ val androidProvider = storageProvider as net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider
+ // Use reflection to access private context field
+ val contextField = androidProvider.javaClass.getDeclaredField("context")
+ contextField.isAccessible = true
+ val context = contextField.get(androidProvider) as android.content.Context
+ VaultPin(context)
+ }
// endregion
diff --git a/apps/mobile-app/android/app/src/main/res/drawable/pin_dot_empty.xml b/apps/mobile-app/android/app/src/main/res/drawable/pin_dot_empty.xml
new file mode 100644
index 000000000..aee425dfe
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/res/drawable/pin_dot_empty.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<shape xmlns:android="http://schemas.android.com/apk/res/android"
+ android:shape="oval">
+ <stroke
+ android:width="2dp"
+ android:color="?android:attr/textColorSecondary" />
+ <size
+ android:width="16dp"
+ android:height="16dp" />
+</shape>
diff --git a/apps/mobile-app/android/app/src/main/res/drawable/pin_dot_filled.xml b/apps/mobile-app/android/app/src/main/res/drawable/pin_dot_filled.xml
new file mode 100644
index 000000000..f221308ba
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/res/drawable/pin_dot_filled.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<shape xmlns:android="http://schemas.android.com/apk/res/android"
+ android:shape="oval">
+ <solid android:color="@color/primary" />
+ <stroke
+ android:width="2dp"
+ android:color="@color/primary" />
+ <size
+ android:width="16dp"
+ android:height="16dp" />
+</shape>
diff --git a/apps/mobile-app/android/app/src/main/res/layout/activity_pin_unlock.xml b/apps/mobile-app/android/app/src/main/res/layout/activity_pin_unlock.xml
new file mode 100644
index 000000000..84282d1b6
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/res/layout/activity_pin_unlock.xml
@@ -0,0 +1,246 @@
+<?xml version="1.0" encoding="utf-8"?>
+<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:app="http://schemas.android.com/apk/res-auto"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:background="?android:attr/colorBackground"
+ tools:context=".pinunlock.PinUnlockActivity">
+
+ <!-- Header with Cancel Button -->
+ <Button
+ android:id="@+id/cancelButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/pin_cancel"
+ android:textColor="@color/primary"
+ style="?android:attr/borderlessButtonStyle"
+ android:layout_marginTop="20dp"
+ android:layout_marginEnd="20dp"
+ app:layout_constraintTop_toTopOf="parent"
+ app:layout_constraintEnd_toEndOf="parent" />
+
+ <!-- Logo -->
+ <ImageView
+ android:id="@+id/logoImageView"
+ android:layout_width="80dp"
+ android:layout_height="80dp"
+ android:src="@mipmap/ic_launcher"
+ android:contentDescription="@string/aliasvault_icon"
+ app:layout_constraintTop_toBottomOf="@id/cancelButton"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ android:layout_marginTop="60dp" />
+
+ <!-- Title -->
+ <TextView
+ android:id="@+id/titleTextView"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/pin_unlock_vault"
+ android:textSize="24sp"
+ android:textStyle="bold"
+ android:textColor="?android:attr/textColorPrimary"
+ app:layout_constraintTop_toBottomOf="@id/logoImageView"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ android:layout_marginTop="20dp" />
+
+ <!-- Subtitle -->
+ <TextView
+ android:id="@+id/subtitleTextView"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:text="@string/pin_enter_to_unlock"
+ android:textSize="16sp"
+ android:textColor="?android:attr/textColorSecondary"
+ android:gravity="center"
+ app:layout_constraintTop_toBottomOf="@id/titleTextView"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ android:layout_marginTop="8dp"
+ android:layout_marginStart="40dp"
+ android:layout_marginEnd="40dp" />
+
+ <!-- PIN Dots Container (for fixed-length PINs) -->
+ <LinearLayout
+ android:id="@+id/pinDotsContainer"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal"
+ android:gravity="center"
+ app:layout_constraintTop_toBottomOf="@id/subtitleTextView"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ android:layout_marginTop="32dp"
+ android:visibility="visible" />
+
+ <!-- PIN Text View (for variable-length PINs) -->
+ <TextView
+ android:id="@+id/pinTextView"
+ android:layout_width="wrap_content"
+ android:layout_height="48dp"
+ android:text="----"
+ android:textSize="42sp"
+ android:textStyle="bold"
+ android:textColor="?android:attr/textColorPrimary"
+ android:letterSpacing="0.2"
+ android:gravity="center"
+ app:layout_constraintTop_toBottomOf="@id/subtitleTextView"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ android:layout_marginTop="32dp"
+ android:visibility="gone" />
+
+ <!-- Error Message -->
+ <TextView
+ android:id="@+id/errorTextView"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:textSize="14sp"
+ android:textColor="@android:color/holo_red_dark"
+ android:gravity="center"
+ android:visibility="gone"
+ app:layout_constraintTop_toBottomOf="@id/pinDotsContainer"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ android:layout_marginTop="12dp"
+ android:layout_marginStart="40dp"
+ android:layout_marginEnd="40dp" />
+
+ <!-- Numpad -->
+ <LinearLayout
+ android:id="@+id/numpadContainer"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ android:gravity="center"
+ app:layout_constraintBottom_toBottomOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ android:layout_marginBottom="40dp"
+ android:layout_marginStart="40dp"
+ android:layout_marginEnd="40dp">
+
+ <!-- Row 1: 1-3 -->
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="60dp"
+ android:orientation="horizontal"
+ android:gravity="center"
+ android:layout_marginBottom="12dp">
+
+ <Button
+ android:id="@+id/btn1"
+ style="@style/PinNumpadButton"
+ android:text="1" />
+
+ <Button
+ android:id="@+id/btn2"
+ style="@style/PinNumpadButton"
+ android:text="2" />
+
+ <Button
+ android:id="@+id/btn3"
+ style="@style/PinNumpadButton"
+ android:text="3" />
+ </LinearLayout>
+
+ <!-- Row 2: 4-6 -->
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="60dp"
+ android:orientation="horizontal"
+ android:gravity="center"
+ android:layout_marginBottom="12dp">
+
+ <Button
+ android:id="@+id/btn4"
+ style="@style/PinNumpadButton"
+ android:text="4" />
+
+ <Button
+ android:id="@+id/btn5"
+ style="@style/PinNumpadButton"
+ android:text="5" />
+
+ <Button
+ android:id="@+id/btn6"
+ style="@style/PinNumpadButton"
+ android:text="6" />
+ </LinearLayout>
+
+ <!-- Row 3: 7-9 -->
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="60dp"
+ android:orientation="horizontal"
+ android:gravity="center"
+ android:layout_marginBottom="12dp">
+
+ <Button
+ android:id="@+id/btn7"
+ style="@style/PinNumpadButton"
+ android:text="7" />
+
+ <Button
+ android:id="@+id/btn8"
+ style="@style/PinNumpadButton"
+ android:text="8" />
+
+ <Button
+ android:id="@+id/btn9"
+ style="@style/PinNumpadButton"
+ android:text="9" />
+ </LinearLayout>
+
+ <!-- Row 4: Empty, 0, Backspace -->
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="60dp"
+ android:orientation="horizontal"
+ android:gravity="center">
+
+ <!-- Empty space -->
+ <View
+ android:layout_width="0dp"
+ android:layout_height="60dp"
+ android:layout_weight="1" />
+
+ <Button
+ android:id="@+id/btn0"
+ style="@style/PinNumpadButton"
+ android:text="0" />
+
+ <Button
+ android:id="@+id/btnBackspace"
+ style="@style/PinNumpadButton"
+ android:text="⌫"
+ android:textSize="24sp" />
+ </LinearLayout>
+ </LinearLayout>
+
+ <!-- Loading Overlay -->
+ <View
+ android:id="@+id/loadingOverlay"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:background="#4D000000"
+ android:visibility="gone"
+ android:clickable="true"
+ android:focusable="true" />
+
+ <!-- Loading Spinner -->
+ <ProgressBar
+ android:id="@+id/progressBar"
+ android:layout_width="48dp"
+ android:layout_height="48dp"
+ android:indeterminate="true"
+ android:indeterminateTint="@color/primary"
+ android:visibility="gone"
+ app:layout_constraintTop_toTopOf="parent"
+ app:layout_constraintBottom_toBottomOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintEnd_toEndOf="parent" />
+
+</androidx.constraintlayout.widget.ConstraintLayout>
diff --git a/apps/mobile-app/android/app/src/main/res/values/colors.xml b/apps/mobile-app/android/app/src/main/res/values/colors.xml
index af3daf2bd..2dad46ed3 100644
--- a/apps/mobile-app/android/app/src/main/res/values/colors.xml
+++ b/apps/mobile-app/android/app/src/main/res/values/colors.xml
@@ -32,4 +32,7 @@
<!-- Loading overlay background (light mode: white with 80% opacity) -->
<color name="av_loading_overlay">#CCFFFFFF</color>
+
+ <!-- Alias for primary color (used in PIN unlock) -->
+ <color name="primary">@color/av_primary</color>
</resources>
diff --git a/apps/mobile-app/android/app/src/main/res/values/dimens.xml b/apps/mobile-app/android/app/src/main/res/values/dimens.xml
new file mode 100644
index 000000000..509965656
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/res/values/dimens.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <!-- PIN unlock dimensions -->
+ <dimen name="pin_dot_size">16dp</dimen>
+ <dimen name="pin_dot_spacing">6dp</dimen>
+</resources>
diff --git a/apps/mobile-app/android/app/src/main/res/values/strings.xml b/apps/mobile-app/android/app/src/main/res/values/strings.xml
index 279d9fae2..be9b42ba6 100644
--- a/apps/mobile-app/android/app/src/main/res/values/strings.xml
+++ b/apps/mobile-app/android/app/src/main/res/values/strings.xml
@@ -71,4 +71,13 @@
<string name="error_vault_unlock_failed">Failed to unlock vault</string>
<string name="error_biometric_cancelled">Biometric authentication cancelled</string>
<string name="error_encryption_key_failed">Failed to retrieve encryption key</string>
+
+ <!-- PIN unlock -->
+ <string name="pin_unlock_vault">Unlock Vault</string>
+ <string name="pin_enter_to_unlock">Enter your PIN to unlock your vault</string>
+ <string name="pin_cancel">Cancel</string>
+ <string name="pin_unlock_failed">Unlock failed</string>
+ <string name="pin_not_configured">PIN unlock is not configured</string>
+ <string name="pin_locked_max_attempts">PIN locked after too many failed attempts</string>
+ <string name="pin_incorrect_attempts_remaining">Incorrect PIN. %d attempts remaining</string>
</resources>
\ No newline at end of file
diff --git a/apps/mobile-app/android/app/src/main/res/values/styles.xml b/apps/mobile-app/android/app/src/main/res/values/styles.xml
index 646f14d48..8430c19e4 100644
--- a/apps/mobile-app/android/app/src/main/res/values/styles.xml
+++ b/apps/mobile-app/android/app/src/main/res/values/styles.xml
@@ -32,4 +32,15 @@
<item name="android:windowLightStatusBar">true</item>
<item name="android:windowLightNavigationBar">true</item>
</style>
+ <style name="PinNumpadButton">
+ <item name="android:layout_width">0dp</item>
+ <item name="android:layout_height">60dp</item>
+ <item name="android:layout_weight">1</item>
+ <item name="android:layout_marginStart">6dp</item>
+ <item name="android:layout_marginEnd">6dp</item>
+ <item name="android:background">@color/av_accent_background</item>
+ <item name="android:textSize">24sp</item>
+ <item name="android:textStyle">bold</item>
+ <item name="android:textColor">?android:attr/textColorPrimary</item>
+ </style>
</resources>
\ No newline at end of file