Android Biometric API 新手使用指南

一、核心功能与使用场景

Biometric API 提供标准化的生物识别认证(指纹、人脸、虹膜等)支持,适用于以下场景:

  1. 应用登录验证

    • 替代传统密码,提升用户体验与安全性
  2. 支付/交易确认

    • 关键操作前的身份验证(如转账、修改密码)
  3. 敏感数据访问

    • 加密文件/数据库前的用户身份校验
  4. 多因素认证(MFA)​

    • 结合短信验证码、硬件密钥等增强安全性

二、基础使用示例

1. 添加依赖

gradle 复制代码
// build.gradle (app)
dependencies {
    implementation "androidx.biometric:biometric:1.1.0"
}

2. 检查设备支持情况

kotlin 复制代码
fun isBiometricAvailable(context: Context): Boolean {
    val biometricManager = BiometricManager.from(context)
    return biometricManager.canAuthenticate(
        BiometricManager.Authenticators.BIOMETRIC_STRONG
    ) == BiometricManager.BIOMETRIC_SUCCESS
}

3. 初始化 BiometricPrompt

kotlin 复制代码
private lateinit var biometricPrompt: BiometricPrompt
private lateinit var promptInfo: BiometricPrompt.PromptInfo

fun setupBiometricAuth(activity: AppCompatActivity) {
    // 初始化认证回调
    val executor = ContextCompat.getMainExecutor(activity)
    biometricPrompt = BiometricPrompt(activity, executor,
        object : BiometricPrompt.AuthenticationCallback() {
            override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                // 认证成功处理
            }

            override fun onAuthenticationFailed() {
                // 临时性失败(如指纹未识别)
            }

            override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                // 不可恢复错误(如多次失败)
            }
        })

    // 构建提示信息
    promptInfo = BiometricPrompt.PromptInfo.Builder()
        .setTitle("生物识别登录")
        .setSubtitle("请验证已有生物特征")
        .setNegativeButtonText("使用密码") // 备用验证选项
        .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)
        .build()
}

// 触发认证
fun startBiometricAuth() {
    biometricPrompt.authenticate(promptInfo)
}

三、版本兼容性处理

Android 版本 支持情况
API 23-27 使用 AndroidX Biometric 库兼容支持指纹
API 28+ 原生支持 BiometricPrompt,兼容指纹、人脸等
API 29+ 新增 BIOMETRIC_STRONGBIOMETRIC_WEAK 分级
API 30+ 要求显式声明 BIOMETRIC_* 权限

兼容代码示例

kotlin 复制代码
fun getSupportedAuthenticators(): Int {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        BiometricManager.Authenticators.BIOMETRIC_STRONG or
        BiometricManager.Authenticators.DEVICE_CREDENTIAL
    } else {
        BiometricManager.Authenticators.BIOMETRIC_STRONG
    }
}

四、注意事项与最佳实践

  1. 权限声明

    xml 复制代码
    <uses-permission android:name="android.permission.USE_BIOMETRIC" />
  2. 备用验证方式

    kotlin 复制代码
    .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG or
        BiometricManager.Authenticators.DEVICE_CREDENTIAL)
  3. 错误处理

    kotlin 复制代码
    override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
        when (errorCode) {
            BiometricPrompt.ERROR_NEGATIVE_BUTTON -> 
                // 用户选择备用验证
            BiometricPrompt.ERROR_LOCKOUT -> 
                // 认证锁定(30秒后重试)
            BiometricPrompt.ERROR_LOCKOUT_PERMANENT -> 
                // 需用户使用备用方式解锁
        }
    }
  4. 厂商定制适配

    • 华为设备 :部分旧机型需调用 HuaweiFingerprintManager
    • 三星设备 :虹膜识别需额外声明 <uses-feature android:name="com.samsung.android.sdk.iris" />
  5. 安全存储

    • 结合 AndroidKeyStore 存储加密密钥
    kotlin 复制代码
    fun generateSecretKey(): SecretKey {
        val keyGenerator = KeyGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"
        )
        keyGenerator.init(
            KeyGenParameterSpec.Builder(
                "biometric_key",
                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
            ).apply {
                setUserAuthenticationRequired(true)
                setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
            }.build()
        )
        return keyGenerator.generateKey()
    }

五、进阶功能实现

1. 加密数据绑定认证

kotlin 复制代码
val cryptoObject = BiometricPrompt.CryptoObject(cipher)
biometricPrompt.authenticate(promptInfo, cryptoObject)

2. 主动取消认证

kotlin 复制代码
fun cancelBiometricAuth() {
    biometricPrompt.cancelAuthentication()
}

3. 生物识别强度分级

kotlin 复制代码
fun checkBiometricStrength(context: Context): String {
    return when (BiometricManager.from(context).canAuthenticate(
        BiometricManager.Authenticators.BIOMETRIC_STRONG)) {
        BiometricManager.BIOMETRIC_SUCCESS -> "强生物识别"
        else -> "弱生物识别或未支持"
    }
}

六、测试与调试

  1. 模拟器测试

    • 启用虚拟指纹:Android Studio → AVD Manager → 选择设备 → 设置指纹
  2. ADB命令触发

    bash 复制代码
    adb -e emu finger touch <finger_id>
  3. 自动化测试

    kotlin 复制代码
    @Test
    fun testBiometricAuth() {
        val scenario = ActivityScenario.launch(MainActivity::class.java)
        scenario.onActivity { activity ->
            activity.startBiometricAuth()
            // 模拟认证成功
            val result = BiometricPrompt.AuthenticationResult(
                BiometricPrompt.CryptoObject(cipher))
            activity.biometricCallback.onAuthenticationSucceeded(result)
        }
    }

七、总结

  • 核心价值:平衡安全性与用户体验,降低传统密码的依赖
  • 推荐实践
    • 始终提供备用验证方式
    • 结合硬件级密钥存储(AndroidKeyStore)
    • 遵循生物识别分级策略(BIOMETRIC_STRONG/WEAK)
  • 厂商适配:针对主流厂商设备进行兼容性测试

通过合理使用 Biometric API,开发者可在保障安全性的前提下,为用户提供无缝的认证体验。

更多分享

  1. 一文吃透Kotlin中冷流(Clod Flow)和热流(Hot Flow)
  2. 一文带你吃透Kotlin协程的launch()和async()的区别
  3. 一文带你吃透接口(Interface)结合 @AutoService 与 ServiceLoader 详解
  4. 一文带你吃透Android中显示Intent与隐式Intent的区别
  5. 一文带你吃透Android View绘制流程与原理详解
相关推荐
保护我方三四5 分钟前
ART | GC Configuration
android
独行soc7 分钟前
2025年渗透测试面试题总结-某快手-安全工程师(题目+回答)
网络·数据库·python·安全·面试·职场和发展·红蓝攻防
燕雀安知鸿鹄之志哉.36 分钟前
ctfshow WEB web5
安全·web安全·网络安全·系统安全
weixin_391336901 小时前
gdb 调试mysql
android·mysql·adb
ufo00l2 小时前
Android buildToolsVersion 会影响什么
android
技术蔡蔡2 小时前
Android项目如何添加Flutter Module
android·flutter
dora2 小时前
Android数据缓存框架 - 内存缓存与数据的发布订阅
android·开源·github
_一条咸鱼_2 小时前
Android Compose 框架的列表与集合模块之懒加载列表深入剖析(四十五)
android
Sinokap2 小时前
Let’s Encrypt 宣布推出短期证书与 IP 地址支持,推动 Web 安全迈向新高度
前端·tcp/ip·安全·ocr
屎派克3 小时前
物理安全——问答
安全