使用新的 androidx.BiometricPrompt 通过生物识别注册使密钥无效

Axb*_*rov 5 android android-keystore android-biometric-prompt

我正在使用新androidx.BiometricPromt库通过指纹实现身份验证。如果用户添加新指纹或删除指纹,我想使密钥无效。我正在创建这样的密钥:

fun getSecretKey(shouldCreate: Boolean): Key {
    val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE)
    keyStore.load(null)
    return if (shouldCreate) {
        createSecretKey(keyStore)
    } else {
        keyStore.getKey(ALIAS_BIOMETRICS, null)
    }
}

private fun createSecretKey(keystore: KeyStore): Key {
    val builder = KeyGenParameterSpec.Builder(
        ALIAS_BIOMETRICS,
        KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
    )
        .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
        .setUserAuthenticationRequired(true)
        .setUserAuthenticationValidityDurationSeconds(5)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        builder.setInvalidatedByBiometricEnrollment(true)
        builder.setUserAuthenticationValidWhileOnBody(true)
    }

    val keyGenerator =
        KeyGenerator.getInstance(keyAlgorithm, keystore.provider)
    keyGenerator
        .init(builder.build())
    return keyGenerator.generateKey()
}
Run Code Online (Sandbox Code Playgroud)

我正在开始这样的生物识别扫描过程:

val info = BiometricPrompt.PromptInfo.Builder()
    .setTitle(context.getString(R.string.biometric_dialog_title))
    .setSubtitle(context.getString(R.string.biometric_dialog_subtitle))
    .setNegativeButtonText(context.getString(R.string.biometric_dialog_cancel))
    .build()

biometricPrompt = when (screen) {
    is FragmentActivity -> BiometricPrompt(screen, { it.run() }, this)
    is Fragment -> BiometricPrompt(screen, { it.run() }, this)
    else -> throw IllegalArgumentException("Screen type must be FragmentActivity or Fragment")
}

biometricPrompt?.authenticate(info)
Run Code Online (Sandbox Code Playgroud)

我想开始,biometricPromt?.authenticate(info, cryptoObject)但在这种情况下,我需要初始化 Cipher 并抛出异常UserNotAuthenticated。用户成功扫描生物识别后,我正在创建 SecretKey 并用于加密。然后我正在更改指纹(添加一些新指纹并删除)。解密过程就像加密一样,但只有在获取密钥时,我才不会创建新的,而是从密钥库中获取的。虽然我改变了指纹,但一切都很好。如果用户更改了他设备中的指纹,我想拒绝解密。如何使用 androidx.BiometricPrompt 库实现此功能?