0


Android 生物识别:构建一个存储用户敏感信息的安全应用

在这里插入图片描述

前言

在当今数字时代,随着科技的不断发展,用户敏感信息尤为重要。从指纹到面部识别,再到虹膜扫描,生物识别技术为我们带来了便捷性和安全性。本次将构建一个简易的账户信息应用,运用生物识别技术来提高信息的安全性。

什么是 Biometric ?

Biometric 是一组 API 和框架,旨在为 Android 应用程序提供生物识别功能,以提高用户安全性和便利性。这些生物识别技术通常包括指纹识别、面部识别和虹膜扫描等。

三种不同的生物识别身份验证类型:

  • BIOMETRIC_STRONG:强类型识别验证它要求用户提供强大的生物识别信息,例如指纹和虹膜扫描,这使得难以伪造和绕过验证。它提供了高级别安全性,适合处理敏感数据和交易类型的应用。
  • BIOMETRIC_WEAK:弱类型识别验证使用人脸识别等不太安全的验证方法,与强类型相比可能更容易欺骗或绕过验证,此方式适合安全性较低的应用。
  • DEVICE_CREDENTIAL:此验证方式不涉及生物识别,而是依赖于手机设备的安全性,例如 PIN、密码或图案。当手机不具备生物识别技术时,可使用此方式。

示例

在开始之前先来看看成品效果如何,当我们启动应用之后会立马弹出验证弹窗进行识别身份,在未完成识别之前,应用内部的信息都是无法查看的。
在这里插入图片描述

添加依赖库

在模块级别的 build.gradle 文件中添加以下依赖:

  1. buildscript {
  2. dependencies {
  3. classpath "com.google.dagger:hilt-android-gradle-plugin:2.38.1"}}
  4. plugins {...}

在项目级别的 build.gradle 文件中添加以下依赖:

  1. plugins {...
  2. id 'dagger.hilt.android.plugin'
  3. id 'kotlin-kapt'
  4. }
  5. android {...}
  6. dependencies {...// Room
  7. implementation "androidx.room:room-runtime:2.4.3"
  8. kapt "androidx.room:room-compiler:2.4.3"
  9. implementation "androidx.room:room-ktx:2.4.3"
  10. annotationProcessor "androidx.room:room-compiler:2.4.3"// Dagger + Hilt
  11. implementation "com.google.dagger:hilt-android:2.38.1"
  12. kapt "com.google.dagger:hilt-compiler:2.38.1"
  13. implementation "androidx.hilt:hilt-navigation-compose:1.0.0"
  14. implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03"
  15. kapt "androidx.hilt:hilt-compiler:1.0.0"//生物识别
  16. implementation "androidx.biometric:biometric:1.1.0"}

编写数据库部分

创建存储账户信息实体类 AccountEntity 、数据访问对象 AccountDao 以及 Room 数据库文件 AccountDatabase 。

  1. @Entity(tableName ="account")dataclassAccountEntity(@PrimaryKey(autoGenerate =true)val id: Int?=null,val type: String,val account: String,val password: String
  2. )//------------------------------@Daointerface AccountDao {@InsertsuspendfunaddAccount(account: AccountEntity)@Query("SELECT * FROM account")fungetAccounts():Flow<List<AccountEntity>>@DeletesuspendfundeleteAccount(account: AccountEntity)}//------------------------------@Database(
  3. entities =[AccountEntity::class],
  4. version =1)abstractclass AccountDatabase :RoomDatabase(){abstractfungetDao(): AccountDao
  5. companionobject{constval DATABASE_NAME ="accounts_db"}}

依赖注入

创建 DatabaseModule 单例对象,使用 Hilt 提供的注解标记,它负责管理全局应用中的单例对象,里面有一个提供数据库实例的方法,在需要的地方直接在构造器声明即可,它会自动注入该对象。

  1. @Module@InstallIn(SingletonComponent::class)object DatabaseModule {@Provides@SingletonfunprovideAccountDatabase(@ApplicationContext context: Context): AccountDatabase {return Room.databaseBuilder(
  2. context,
  3. AccountDatabase::class.java,
  4. AccountDatabase.DATABASE_NAME
  5. ).build()}}

编写业务逻辑

在 MainViewModel 中使用特有注解 HiltViewModel 并注入数据库实例对象。注意:一般操作数据库是在 Repository 中进行的,这里为了演示就简化了,直接在 ViewModel 中操作。

  1. @HiltViewModelclass MainViewModel @Injectconstructor(privateval db:AccountDatabase
  2. ):ViewModel(){//账户列表privateval _accounts = mutableStateOf<List<AccountEntity>>(emptyList())val accounts: State<List<AccountEntity>>= _accounts
  3. init{getAllAccounts()}//添加账户funaddAccount(
  4. type: String,
  5. account: String,
  6. password: String
  7. ){
  8. viewModelScope.launch{
  9. db.getDao().addAccount(AccountEntity(
  10. type=type,
  11. account=account,
  12. password=password
  13. ))}}//删除账户fundeleteAccount(account: AccountEntity){
  14. viewModelScope.launch{
  15. db.getDao().deleteAccount(account)}}//获取所有账户privatefungetAllAccounts(){
  16. viewModelScope.launch{
  17. db.getDao().getAccounts().collect{ result ->
  18. _accounts.value = result
  19. }}}}

使用 Biometric API(核心)

创建 BiometricPrompt 实例,它是 AndroidX 中提供的组件,可帮助我们轻松快速的将生物识别添加到应用中。

  • BiometricPrompt.PromptInfo.Builder() :用于创建提示信息,提示框的标题和描述以及配置身份验证的方式。
  • BiometricPrompt 实例通过 activity, executor, callback 三部分构造,其中 executor 负责主线程上的回调处理,callback 的类型为 BiometricPrompt.AuthenticationCallback ,回调三个身份验证处理的回调方法。
  • biometricPrompt.authenticate(promptInfo) 调用身份验证方法,传入提示信息向用户显示身份验证对话框。
  1. object BiometricHelper {/** 创建提示信息 **/privatefuncreatePromptInfo(): BiometricPrompt.PromptInfo =
  2. BiometricPrompt.PromptInfo.Builder().setTitle("SecretAccountApp").setDescription("使用你的指纹或者面部来验证你的身份").setAllowedAuthenticators(BIOMETRIC_STRONG or BIOMETRIC_WEAK or DEVICE_CREDENTIAL).build()//setConfirmationRequired(true)//setNegativeButtonText("取消")/** 创建生物识别提示 **/funshowBiometricPrompt(
  3. activity: AppCompatActivity,
  4. onSuccess:(BiometricPrompt.AuthenticationResult)-> Unit
  5. ){val executor = ContextCompat.getMainExecutor(activity)val callback =object: BiometricPrompt.AuthenticationCallback(){overridefunonAuthenticationError(
  6. errorCode: Int,
  7. errString: CharSequence
  8. ){super.onAuthenticationError(errorCode, errString)// 处理身份验证错误
  9. Log.e("HGM","onAuthenticationError: $errString")}overridefunonAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult){super.onAuthenticationSucceeded(result)// 处理身份验证成功onSuccess(result)}overridefunonAuthenticationFailed(){super.onAuthenticationFailed()// 处理身份验证失败
  10. Log.e("HGM","onAuthenticationFailed: 验证失败")}}returnBiometricPrompt(activity, executor, callback).authenticate(createPromptInfo())}}

注意:创建 PromptInfo 实例时不能同时调用 setNegativeButtonText()和 setAllowedAuthenticators() 一旦你设置了否定取消文本按钮,意味着结束身份验证,而后者可以设置使用多个身份验证方法。

编写UI

由于本文得侧重点不在于 UI,所以直接贴上代码。

这里添加一个生命周期的监听者,在应用启动的时候自动执行身份验证,当应用返回到桌面或者重新启动会重置状态,每次进入都需要进行验证。

  1. @ComposablefunOnLifecycleEvent(
  2. lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
  3. onEvent:(LifecycleOwner, Lifecycle.Event)-> Unit
  4. ){DisposableEffect(lifecycleOwner){val observer = LifecycleEventObserver { source, event ->onEvent(source, event)}
  5. lifecycleOwner.lifecycle.addObserver(observer)
  6. onDispose {
  7. lifecycleOwner.lifecycle.removeObserver(observer)}}}

页面由一个简单的列表和按钮组成,代码过长重点部分:

  1. @OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)@ComposablefunAccountScreen(
  2. viewModel: MainViewModel =hiltViewModel()){val activity = LocalContext.current as AppCompatActivity
  3. // 是否显示账号输入框var showDialog by remember {mutableStateOf(false)}// 身份验证的状态val authorized = remember {mutableStateOf(false)}// 执行身份验证val authorize:()-> Unit ={
  4. BiometricHelper.showBiometricPrompt(activity){
  5. authorized.value =true}}// 模糊值val blurValue byanimateDpAsState(
  6. targetValue =if(authorized.value)0.dp else15.dp,
  7. animationSpec =tween(500))// 监听应用的声明周期
  8. OnLifecycleEvent { _, event ->when(event){
  9. Lifecycle.Event.ON_RESUME ->authorize()
  10. Lifecycle.Event.ON_PAUSE -> authorized.value =falseelse-> Unit
  11. }}Scaffold(
  12. floatingActionButton ={
  13. Column {FloatingActionButton(onClick ={
  14. showDialog =true}){Icon(
  15. imageVector = Icons.Default.Add,
  16. contentDescription =null)}Spacer(modifier = Modifier.height(12.dp))FloatingActionButton(onClick ={authorize()}){Icon(
  17. imageVector = Icons.Default.Lock,
  18. contentDescription =null)}}}){ innerPadding ->Box(
  19. modifier = Modifier
  20. .fillMaxSize().padding(innerPadding)){LazyColumn(
  21. modifier = Modifier
  22. .fillMaxSize().padding(12.dp),
  23. verticalArrangement = Arrangement.spacedBy(12.dp)){items(viewModel.accounts.value){Box(
  24. modifier = Modifier
  25. .animateItemPlacement(tween(500)).fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(MaterialTheme.colorScheme.primary).padding(16.dp).blur(
  26. radius = blurValue,
  27. edgeTreatment = BlurredEdgeTreatment.Unbounded
  28. )){...}}}}if(showDialog){Dialog(
  29. onDismissRequest ={ showDialog =false}){...}}}}

修改 MainActivity 的继承父类为 AppCompatActivity 并且修改主题样式,因为创建 BiometricPrompt 时需要类型为 FragmentActivity 参数,AppCompatActivity 是 FragmentActivity 的子类并扩展了它。

  1. @AndroidEntryPointclass MainActivity :AppCompatActivity(){overridefunonCreate(savedInstanceState: Bundle?){super.onCreate(savedInstanceState)
  2. setContent {
  3. SecretAccountAppTheme {Surface(
  4. modifier = Modifier.fillMaxSize(),
  5. color = MaterialTheme.colorScheme.background
  6. ){AccountScreen()}}}}}

在这里插入图片描述
自定义 MyApp 继承 Application 程序类,使用 @HiltAndroidApp 注解作为标识应用程序的主类,这里没有初始化工作就不需要写东西,在注册清单中应用它。

  1. <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"><!-- 开启权限 --><uses-permission android:name="android.permission.USE_BIOMETRIC"/><application
  3. android:name=".MyApp"...>....</application></manifest>

准备测试指纹

如果你使用模拟器,需要打开设置->安全中先添加 PIN 码后,添加一个指纹用于测试。

添加测试指纹

运行效果

使用刚才添加的指纹一进行验证,通过后会显示应用内的信息,如视频中使用指纹二会显示验证失败。并且每次进入应用都需要进行身份验证,保证了数据不会泄露。如果你想使用面容验证,那就需要删除掉你的指纹,添加一个面容数据,它会自动识别你已添加的生物识别数据。

最后这只是一个简易的实例项目,更多内容请结合实际项目,欢迎 Github 提交 Issue。

生物识别运行效果

源码地址:

https://github.com/AAnthonyyyy/SecretAccountApp

官方文档:

https://developer.android.com/training/sign-in/biometric-auth?hl=zh-cn

关注我,与你分享更多技术文章。麻烦右下角区域点个【赞】支持一下吧!更多内容请关注下方微信公众号。
在这里插入图片描述

标签: android 安全 kotlin

本文转载自: https://blog.csdn.net/weixin_49767743/article/details/135070918
版权归原作者 AAnthonyyy 所有, 如有侵权,请联系我们删除。

“Android 生物识别:构建一个存储用户敏感信息的安全应用”的评论:

还没有评论