在Kotlin中如何判定新指纹注册或旧指纹删除的状态?
生物特征录入变更检测解决方案
Android 原生BiometricManager提供的canAuthenticate()接口本身未预置指纹/生物特征新增、删除对应的专属错误码,你当前代码覆盖的枚举值仅包含硬件状态、可用性、未录入、安全更新、认证成功几类官方预设状态,自然无法检测到录入变更的场景。
解决方案
- 方案1:通过绑定生物特征的KeyStore密钥检测变更(优先推荐,兼容API 23及以上)
原理:生成密钥时设置setInvalidatedByBiometricEnrollment(true)(该配置为默认值),只要系统内录入的生物特征发生新增、删除变更,该密钥会自动失效,通过校验密钥有效性即可判断是否发生录入变更。
// 首次生物认证成功后,生成绑定生物特征的密钥 fun generateBiometricBoundKey() { val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") val keyGenParameterSpec = KeyGenParameterSpec.Builder( "biometric_bound_key", KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT ) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7) .setUserAuthenticationRequired(true) // 核心配置:生物特征录入变更后密钥自动失效 .setInvalidatedByBiometricEnrollment(true) .build() keyGenerator.init(keyGenParameterSpec) keyGenerator.generateKey() } // 检测生物特征是否发生新增/删除变更 fun isBiometricEnrollmentChanged(): Boolean { return try { val keyStore = KeyStore.getInstance("AndroidKeyStore") keyStore.load(null) keyStore.getKey("biometric_bound_key", null) false } catch (e: KeyPermanentlyInvalidatedException) { // 捕获到该异常说明生物特征已变更 true } catch (e: Exception) { false } }
- 方案2:优化原有生物状态检测方法的兼容性
你当前使用的无参canAuthenticate()已在API 30中被废弃,建议替换为带认证类型参数的重载方法,覆盖更多系统版本场景:
fun checkBiometricFeatureState(biometricManager: BiometricManager) : Int? { // 可根据业务安全要求调整为 BIOMETRIC_WEAK val authenticators = BiometricManager.Authenticators.BIOMETRIC_STRONG return when (biometricManager.canAuthenticate(authenticators)) { BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED -> BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED BiometricManager.BIOMETRIC_SUCCESS -> BiometricManager.BIOMETRIC_SUCCESS else -> null } }
- 低版本兼容说明
API 23以下的系统本身不支持生物特征认证的相关安全能力,无需处理录入变更检测。
内容的提问来源于stack exchange,提问作者misterios
相关产品推荐
相关产品推荐

