androidsecurityandroid-keystoreandroid-biometric-promptandroid-biometric

How to replace deprecated KeyGenParameterSpec.Builder.setUserAuthenticationValidityDurationSeconds?


From android 11 setUserAuthenticationValidityDurationSeconds are deprecated in favor of setUserAuthenticationParameters inside KeyGenParameterSpec.Builder but seams there is any support for previous versions.

so, what are best the solution ?

KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(...)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R)
    builder.setUserAuthenticationParameters(timeout, KeyProperties.AUTH_DEVICE_CREDENTIAL | KeyProperties.AUTH_BIOMETRIC_STRONG);
else
    //noinspection deprecation
    builder.setUserAuthenticationValidityDurationSeconds(timeout);

this one?


Solution

  • You don't need to migrate the actual keys, when you are ready to support Android 11 you can just switch to something like this, (don't forget to set compileSdkVersion 30 for the new APIs)

    val timeout = 30 //seconds
    val builder = KeyGenParameterSpec.Builder(...)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        builder.setUserAuthenticationParameters(timeout, 
           KeyProperties.AUTH_DEVICE_CREDENTIAL 
             or KeyProperties.AUTH_BIOMETRIC_STRONG
        )
    } else {
        builder.setUserAuthenticationValidityDurationSeconds(timeout)
    }
    

    You can do this because internally setUserAuthenticationValidityDurationSeconds is doing the same thing. The only exception is if you are calling setUserAuthenticationValidityDurationSeconds with -1 as the timeout. In this case the equivalent with the new API is builder.setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG).

    You can check here the source code for both cases.

    PS: The code above is minAPI 24, you need to wrap the code above in more build checks if you are at a lower API level.