skip to content

In the Android Keystore, what do the timeout and type arguments of setUserAuthenticationParameters control, and why did it replace setUserAuthenticationValidityDurationSeconds?

level: middleimportance: should knowfreq 50%

answer

  1. turned on by another builder call
  2. zero means every single use
  3. a positive value opens a window
  4. AUTH_BIOMETRIC_STRONG and AUTH_DEVICE_CREDENTIAL
  5. API 30; UserNotAuthenticatedException at init

basics

~20 s

With setUserAuthenticationRequired(true), timeout 0 demands authentication for every use through BiometricPrompt and a CryptoObject; a positive timeout allows use for that many seconds after authenticating. Type picks AUTH_BIOMETRIC_STRONG, AUTH_DEVICE_CREDENTIAL or both. API 30 added it, deprecating the seconds-only method.

solid answer

~40 s

`setUserAuthenticationParameters(timeout, type)` only takes effect once `setUserAuthenticationRequired(true)` is set. A `timeout` of `0` means each operation must be authorized individually, which the app does by wrapping the initialised `Cipher` in a `BiometricPrompt.CryptoObject`. A positive `timeout` makes the key usable for that many seconds after any successful authentication of an allowed type; outside the window, `Cipher.init` throws `UserNotAuthenticatedException`. `type` is a bit set of `KeyProperties.AUTH_BIOMETRIC_STRONG` and `AUTH_DEVICE_CREDENTIAL`. The old `setUserAuthenticationValidityDurationSeconds`, deprecated in API 30, could not say which credential counts: it now delegates, mapping `-1` to `(0, AUTH_BIOMETRIC_STRONG)` and a positive value to `(seconds, AUTH_DEVICE_CREDENTIAL or AUTH_BIOMETRIC_STRONG)`. An app with a minSdk below 30 branches on the API level.

code

kotlin · 19 lines
kotlin
fun tokenKeySpec(alias: String): KeyGenParameterSpec {
    val builder = KeyGenParameterSpec.Builder(
        alias,
        KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
    )
        .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
        .setUserAuthenticationRequired(true)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        // Every use needs a Class 3 biometric via BiometricPrompt + CryptoObject.
        builder.setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG)
    } else {
        // API 24-29: -1 maps to the same per-use, biometric-only rule.
        @Suppress("DEPRECATION")
        builder.setUserAuthenticationValidityDurationSeconds(-1)
    }
    return builder.build()
}

go deeper

for a junior

Recall that setUserAuthenticationRequired(true) switches authentication on and that timeout 0 means a prompt for every use.

for a middle

Explain both arguments, the AUTH_* bit set, how the deprecated method maps onto the new one, and where UserNotAuthenticatedException is thrown.

for a senior

Show the API 30 version branch, the retry path after UserNotAuthenticatedException, and that enforcement sits in the Keystore, not the app.

for a principal

Weigh per-use against a time window for each secret, knowing which one keeps background work possible and which one binds every use to the user.

## Turning user authentication on By default an Android Keystore key can be used whether or not the user has authenticated. `KeyGenParameterSpec.Builder.setUserAuthenticationRequired(true)` changes that: the key can then be used only after the user proves their identity with a **secure lock screen credential** (PIN, pattern or password) or a **biometric**. The source adds two conditions: - The key can only be generated while a secure lock screen is set up (`KeyguardManager.isDeviceSecure()`). - The key is **irreversibly invalidated** if the secure lock screen is later disabled or forcibly reset. `setUserAuthenticationParameters(timeout, type)` then says *how* authentication authorizes use. Its documentation is explicit that it has effect only if the key requires user authentication, so calling it without `setUserAuthenticationRequired(true)` does not protect anything. ## The two arguments | `timeout` | `type` | Behaviour | |---|---|---| | `0` | `AUTH_BIOMETRIC_STRONG` | Every operation needs a Class 3 biometric through `BiometricPrompt` with a `CryptoObject` | | `0` | `AUTH_BIOMETRIC_STRONG or AUTH_DEVICE_CREDENTIAL` | Every operation needs authentication; the PIN, pattern or password also counts | | `300` | `AUTH_BIOMETRIC_STRONG` | Usable for 300 seconds after a strong biometric authentication | | `300` | `AUTH_DEVICE_CREDENTIAL or AUTH_BIOMETRIC_STRONG` | Usable for 300 seconds after either kind of authentication | - **`timeout`** is in seconds and must be `0` or larger; the builder throws `IllegalArgumentException` for a negative value. `0` means **auth-per-use**. - **`type`** is a bit set of `KeyProperties.AUTH_BIOMETRIC_STRONG` (Class 3 biometrics) and `KeyProperties.AUTH_DEVICE_CREDENTIAL` (the lock screen credential), both added in API 30. ## What the old method did `setUserAuthenticationValidityDurationSeconds(seconds)` is deprecated in API 30 and points to the new method. In the API 37 source it simply delegates: 1. `-1` becomes `setUserAuthenticationParameters(0, AUTH_BIOMETRIC_STRONG)`: every use, biometric only. 2. Any other value becomes `setUserAuthenticationParameters(seconds, AUTH_DEVICE_CREDENTIAL or AUTH_BIOMETRIC_STRONG)`. The old API could not express a per-use key that also accepts the PIN, or a timed key that accepts only biometrics. The new one can. ## What the app sees at runtime - **Timed key, nobody authenticated recently:** `Cipher.init` throws **`UserNotAuthenticatedException`**, a subclass of `InvalidKeyException`. The app shows `BiometricPrompt.authenticate(promptInfo)` with no `CryptoObject`, allowing the same authenticator types, and then inits the `Cipher` again. - **Per-use key:** `Cipher.init` succeeds, but the operation is authorized only through `BiometricPrompt.authenticate(promptInfo, CryptoObject(cipher))`; the app finishes the work in `onAuthenticationSucceeded`. - **Enforcement is not in the app.** The Keystore enforces these rules outside the app's process; `KeyInfo.isUserAuthenticationRequirementEnforcedBySecureHardware()` reports whether secure hardware enforces them on that device. ## Matching the prompt to the key The key's `type` and the prompt's allowed authenticators should describe the same credentials: - `AUTH_BIOMETRIC_STRONG` pairs with `BiometricManager.Authenticators.BIOMETRIC_STRONG`. - `AUTH_DEVICE_CREDENTIAL` pairs with `DEVICE_CREDENTIAL`; a prompt that allows it cannot also set negative button text. - Before showing anything, call `BiometricManager.canAuthenticate` with the same set; `BIOMETRIC_ERROR_NONE_ENROLLED` means the user has nothing the key would accept yet. - On API 28 and 29, androidx.biometric rejects `BIOMETRIC_STRONG or DEVICE_CREDENTIAL` at `PromptInfo.Builder.build()`, which is one more reason the API 30 branch matters. A prompt that accepts something the key does not leaves the user authenticated yet still facing `UserNotAuthenticatedException` or a failed operation. ## Supporting API 24 to 29 Many apps still set minSdk 24 to 26, so the builder needs a version branch. On API 30 and later use `setUserAuthenticationParameters`; below it, the deprecated method with `-1` gives the same per-use, biometric-only rule. The snippet shows that branch. ## Mistakes to avoid - Calling `setUserAuthenticationParameters` without `setUserAuthenticationRequired(true)`. - Passing `-1` to the new method, as the old one allowed. - Expecting a timed key to need a `CryptoObject`; it needs a recent authentication instead. - Assuming the app can stretch the window: the Keystore enforces it.

  • What should the app do when Cipher.init throws UserNotAuthenticatedException for a 300-second key?
    Show `BiometricPrompt.authenticate(promptInfo)` without a `CryptoObject`, allowing the authenticator types the key accepts. After `onAuthenticationSucceeded`, init the `Cipher` again; for the next 300 seconds the key works without another prompt.
  • Can an auth-per-use key accept the PIN as well as a fingerprint?
    Yes, from API 30: generate it with `setUserAuthenticationParameters(0, AUTH_BIOMETRIC_STRONG or AUTH_DEVICE_CREDENTIAL)` and allow `BIOMETRIC_STRONG or DEVICE_CREDENTIAL` in the prompt. androidx.biometric accepts a `CryptoObject` with device credential only on API 30 and later, and the prompt then has no negative button.

A timed key is like an office badge that keeps doors open for five minutes after you tap in; a per-use key is a safe that wants your fingerprint every time it opens.

  • setUserAuthenticationParameters alone makes a key require authentication
  • Passing -1 to setUserAuthenticationParameters means every use, as before
  • A timed key must be used through a BiometricPrompt CryptoObject
  • The app tracks the validity window, so it can extend it after a prompt
  • AUTH_BIOMETRIC_STRONG accepts any face or fingerprint sensor on the phone

Assumes Android 11 (API 30) or later for setUserAuthenticationParameters and the AUTH_* constants; API 24-29 devices only have the deprecated setUserAuthenticationValidityDurationSeconds.