skip to content

With BiometricPrompt and a CryptoObject, how does an Android time-clock app decrypt its Keystore-protected session token, and what breaks after a new fingerprint is enrolled?

level: seniorimportance: must knowfreq 60%

answer

  1. init before you prompt
  2. wrap the Cipher, then authenticate
  3. finish in onAuthenticationSucceeded
  4. BIOMETRIC_WEAK cannot authorize crypto
  5. KeyPermanentlyInvalidatedException at Cipher.init

basics

~20 s

Init an AES-GCM Cipher in DECRYPT_MODE with the per-use key, wrap it in BiometricPrompt.CryptoObject, call authenticate(promptInfo, cryptoObject) and run doFinal in onAuthenticationSucceeded. After a new enrolment, Cipher.init throws KeyPermanentlyInvalidatedException: delete the key and sign in again.

solid answer

~40 s

The key was generated with `setUserAuthenticationRequired(true)` and timeout `0`, so each operation must be authorized. I load it, call `cipher.init(DECRYPT_MODE, key, GCMParameterSpec(128, iv))`, wrap the cipher in `BiometricPrompt.CryptoObject` and call `authenticate(promptInfo, cryptoObject)`; in `onAuthenticationSucceeded` I call `doFinal` on `result.cryptoObject?.cipher`. For this biometric-only key the prompt allows `BIOMETRIC_STRONG` (the default for crypto); allowing `BIOMETRIC_WEAK`, or `DEVICE_CREDENTIAL` before API 30, makes `authenticate` throw `IllegalArgumentException`. A per-use biometric-only key is invalidated by default when a new biometric is enrolled or all are removed (`setInvalidatedByBiometricEnrollment` defaults to `true`). The failure shows up at `Cipher.init` as `KeyPermanentlyInvalidatedException`, a subclass of `InvalidKeyException`. It is irreversible, so I catch it before the prompt, call `deleteEntry`, send the worker through sign-in and generate a fresh key.

code

kotlin · 26 lines
kotlin
fun promptToDecrypt(activity: FragmentActivity, iv: ByteArray, ciphertext: ByteArray) {
    val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
    val key = keyStore.getKey(ALIAS, null) as? SecretKey ?: return signInAgain()
    val cipher = Cipher.getInstance("AES/GCM/NoPadding")
    try {
        cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, iv))
    } catch (e: KeyPermanentlyInvalidatedException) {
        keyStore.deleteEntry(ALIAS) // the stored ciphertext can never be read again
        return signInAgain()
    }
    val prompt = BiometricPrompt(activity, object : BiometricPrompt.AuthenticationCallback() {
        override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
            val token = result.cryptoObject?.cipher?.doFinal(ciphertext) ?: return
            startShift(token)
        }
        override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
            showClockInFallback(errorCode)
        }
    })
    val info = BiometricPrompt.PromptInfo.Builder()
        .setTitle("Clock in")
        .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)
        .setNegativeButtonText("Use password")
        .build()
    prompt.authenticate(info, BiometricPrompt.CryptoObject(cipher))
}

go deeper

for a junior

Recall the order: init the Cipher, wrap it in a CryptoObject, call authenticate, and call doFinal only in onAuthenticationSucceeded.

for a middle

Explain which authenticator sets work with a CryptoObject, why a negative button is required, and how onAuthenticationFailed differs from onAuthenticationError.

for a senior

Diagnose KeyPermanentlyInvalidatedException after a new fingerprint: where it is thrown, which key configurations it hits, and the deleteEntry plus sign-in recovery.

for a principal

Decide whether the product accepts invalidation on enrolment, and make sure the fallback sign-in path exists before shipping per-use keys.

## Why a CryptoObject is needed A **per-use key** is a Keystore key generated with `setUserAuthenticationRequired(true)` and `setUserAuthenticationParameters(0, AUTH_BIOMETRIC_STRONG)`. The Keystore will not perform an operation with it unless that specific operation has been authorized by the user. `BiometricPrompt.CryptoObject` is how the app ties a fingerprint to an operation: it wraps a `Cipher`, `Signature` or `Mac` that is already initialised (androidx.biometric 1.1.0 also accepts an `IdentityCredential` on API 30), and a successful authentication unlocks that object for use. ## The decrypt flow, step by step 1. **Load the key**: `KeyStore.getInstance("AndroidKeyStore")`, `load(null)`, `getKey(alias, null)`. 2. **Init the Cipher first**: `Cipher.getInstance("AES/GCM/NoPadding")`, then `init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, iv))` with the IV saved at encryption. This is where an invalidated key is reported, before any UI appears. 3. **Build the prompt**: `BiometricPrompt.PromptInfo.Builder()` with `setTitle`, `setAllowedAuthenticators(BIOMETRIC_STRONG)` and `setNegativeButtonText`. A negative button is mandatory unless device credential is allowed, and forbidden when it is; `build()` throws `IllegalArgumentException` otherwise. 4. **Authenticate with the object**: `biometricPrompt.authenticate(info, BiometricPrompt.CryptoObject(cipher))`. 5. **Finish in the callback**: in `onAuthenticationSucceeded(result)`, call `result.cryptoObject?.cipher?.doFinal(ciphertext)` and use the token. Constructed without an `Executor`, `BiometricPrompt` delivers callbacks on the main thread; a constructor overload takes an `Executor` for other threads. Decrypting one short token there is small work, but the Keystore documentation's advice to keep its calls off the main thread still applies to anything larger. ## Checking availability first Before offering fingerprint clock-in, ask `BiometricManager.from(context).canAuthenticate(BIOMETRIC_STRONG)`: - `BIOMETRIC_SUCCESS`: a strong biometric is enrolled and ready. - `BIOMETRIC_ERROR_NONE_ENROLLED`: the hardware exists but nothing is enrolled; on Android 11 (API 30) and later the app can offer `Settings.ACTION_BIOMETRIC_ENROLL` with the allowed authenticators as an extra. - `BIOMETRIC_ERROR_NO_HARDWARE` or `BIOMETRIC_ERROR_HW_UNAVAILABLE`: fall back to password sign-in. The prompt survives configuration changes by default; the library's documentation asks the activity or fragment to construct `BiometricPrompt` again in `onCreate` so the running session gets the new callback. ## What authenticate() refuses androidx.biometric 1.1.0 checks the allowed authenticators before showing anything: | Allowed authenticators | Result with a CryptoObject | |---|---| | `BIOMETRIC_STRONG` | Supported; this is also the default for crypto-based authentication | | includes `BIOMETRIC_WEAK` | `IllegalArgumentException`: Class 2 biometrics cannot authorize crypto | | includes `DEVICE_CREDENTIAL` on API 29 or lower | `IllegalArgumentException`: not supported before API 30 | | `BIOMETRIC_STRONG or DEVICE_CREDENTIAL` on API 30+ | Supported, with no negative button | ## The callbacks - `onAuthenticationSucceeded`: the session is over and the wrapped object is authorized. - `onAuthenticationFailed`: a biometric was presented but **not recognized**. The prompt stays up; do not tear down the screen. - `onAuthenticationError`: an unrecoverable end, such as `ERROR_NEGATIVE_BUTTON`, `ERROR_USER_CANCELED`, `ERROR_LOCKOUT` or `ERROR_LOCKOUT_PERMANENT`. No further events follow. ## After a new fingerprint: KeyPermanentlyInvalidatedException The `KeyGenParameterSpec` documentation says keys that require authentication for **every** use are irreversibly invalidated when a new biometric is enrolled or when no biometrics remain enrolled. `setInvalidatedByBiometricEnrollment` (API 24) controls this and defaults to `true`. Two configurations escape it: passing `false` to that method, or including `AUTH_DEVICE_CREDENTIAL` in `setUserAuthenticationParameters`. Keys with a positive timeout are not affected by enrolment. **Every** authentication-bound key is also invalidated when the secure lock screen is disabled or forcibly reset. The failure surfaces when the app next initialises an operation: `Cipher.init` throws **`KeyPermanentlyInvalidatedException`**. Handling it well means: - **Catch it specifically, and first.** It extends `InvalidKeyException`, so a broader catch placed earlier would swallow it. - **Delete the dead key** with `keyStore.deleteEntry(alias)`; it will never work again, and neither will its ciphertext. - **Re-establish trust another way**: the worker signs in with their password, the server issues a new token, and the app generates a new key and encrypts the new token. Why invalidation on enrolment is the safer default is a design question covered with secure storage; at the API level, the job is to expect the exception and recover cleanly.

  • Why init the Cipher before showing the prompt instead of inside onAuthenticationSucceeded?
    The authentication authorizes the specific operation wrapped in the `CryptoObject`, so that object must exist and be initialised when the prompt starts. Initialising first also surfaces `KeyPermanentlyInvalidatedException` before the worker is asked for a fingerprint that could not help.
  • How do onAuthenticationFailed and onAuthenticationError differ?
    `onAuthenticationFailed` means a biometric was presented but not recognized; the prompt keeps running and the user can try again. `onAuthenticationError` ends the session for good, for example `ERROR_NEGATIVE_BUTTON`, `ERROR_USER_CANCELED` or a lockout, and no further callbacks arrive.
  • Would setInvalidatedByBiometricEnrollment(false) remove the crash?
    It stops invalidation on enrolment, so the exception no longer follows a new fingerprint, but then anyone who knows the device PIN can enrol their own finger and use the key. Removing the screen lock still invalidates the key either way. Whether to accept that is a security design decision, not an API fix.

  • onAuthenticationFailed means the session is over, so close the screen
  • KeyPermanentlyInvalidatedException is thrown by doFinal after a good fingerprint
  • Catch InvalidKeyException first; the invalidation exception is unrelated to it
  • Allowing BIOMETRIC_WEAK lets more phones decrypt with a CryptoObject
  • After invalidation, a reboot or another prompt brings the key back

Assumes androidx.biometric 1.1.0 on API 24 or later; setInvalidatedByBiometricEnrollment is API 24, and a CryptoObject with DEVICE_CREDENTIAL is accepted only from Android 11 (API 30).