***环境复杂度***:指纹识别

一.使用第三方代码

1.第一版

依赖:implementation “androidx.biometric:biometric:1.1.0”

 //TODO 0:获得main的执行者
                Executor mainExecutor = ContextCompat.getMainExecutor(MainActivity.this);
                //TODO 1:获得指纹
                BiometricPrompt prompt = new BiometricPrompt.Builder(MainActivity.this)
                        .setTitle("指纹验证")//标题
                        .setDescription("指纹验证中")//描述
                        //参数一 取消文字  参数二:执行者  参数三:点击事件
                        .setNegativeButton("取消", mainExecutor, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this, "取消了", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .build();
                //TODO 2:校验指纹是否合格
                //参数一:CancellationSignal取消 参数二:执行者  参数三:回调
                prompt.authenticate(new CancellationSignal(), mainExecutor, new BiometricPrompt.AuthenticationCallback() {
                    @Override
                    public void onAuthenticationError(int errorCode, CharSequence errString) {
                        super.onAuthenticationError(errorCode, errString);
                    }

                    @Override
                    public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
                        super.onAuthenticationHelp(helpCode, helpString);
                    }

                    @Override
                    public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {//成功
                        super.onAuthenticationSucceeded(result);
                        Log.d("ytx", "指纹识别成功: ");
                        //跳转页面
                        ARouter.getInstance()
                                .build("/app/Main2Activity")
                                .navigation(MainActivity.this);

                    }

                    @Override
                    public void onAuthenticationFailed() {//失败
                        super.onAuthenticationFailed();
                        Log.d("ytx", "指纹识别失败: ");
                    }
                });

2.第二版:判断

public class Main6Activity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main6);
        //几个问题
        //TODO 1:判断手机是否支持:安卓6。0以后支持
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            Toast.makeText(this, "当前手机不支持指纹解锁", Toast.LENGTH_SHORT).show();
            return;
        }
        //TODO 2:判断手机是否有指纹感应区
        FingerprintManager fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);
        if(!fingerprintManager.isHardwareDetected()){
            Toast.makeText(this, "当前手机不支持指纹感应区", Toast.LENGTH_SHORT).show();
            return;
        }
        //TODO 3:判断手机是否录入指纹
        if(!fingerprintManager.hasEnrolledFingerprints()){
            Toast.makeText(this, "当前手机没有录入指纹", Toast.LENGTH_SHORT).show();
            return;
        }

        //指纹解锁
        //TODO 1:弹出窗体,提示用户录入指纹
        BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder()
                .setTitle("指纹验证")
                .setNegativeButtonText("取消")
                .build();
        //TODO 2:校验此指纹是否合格
        new BiometricPrompt(this, new BiometricPrompt.AuthenticationCallback() {
            @Override
            public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) {
                super.onAuthenticationError(errorCode, errString);
                Toast.makeText(Main6Activity.this, "校验失败", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) {
                super.onAuthenticationSucceeded(result);
                Toast.makeText(Main6Activity.this, "校验成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAuthenticationFailed() {
                super.onAuthenticationFailed();
            }
        })
                .authenticate(promptInfo);//校验


    }
}

二.原生代码

权限:

<uses-permission android:name="android.permission.USE_FINGERPRINT"/>

代码:

package com.bawei.day9day10;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class Main5Activity extends AppCompatActivity {
 private FingerprintManager manager;
 private KeyStore keyStore;
 private static final String DEFAULT_KEY_NAME = "default_key";
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 init();
 }
 private void init() {
 manager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);
 // 判断是否⽀持指纹
 if (isSupportFingerPrint()) {
 initKey();
 initCipher();
 }
 }
 private boolean isSupportFingerPrint() {
 if (Build.VERSION.SDK_INT >= 23) {
 // 权限判断
 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
 Toast.makeText(this, "没有指纹识别权限", Toast.LENGTH_SHORT).show();
 return false;
 }
 // 硬件判断
 if (!manager.isHardwareDetected()) {
 Toast.makeText(this, "没有指纹识别模块", Toast.LENGTH_SHORT).show();
 return false;
 }
 if (!manager.hasEnrolledFingerprints()) {
 Toast.makeText(this, "您⾄少需要在系统设置中添加⼀个指纹", Toast.LENGTH_SHORT).show();
 return false;
 }
 } else {
 Toast.makeText(this, "您的⼿机暂不⽀持指纹识别", Toast.LENGTH_SHORT).show();
 return false;
 }
 return true;
 }
 private void initKey() {
 try {
 keyStore = KeyStore.getInstance("AndroidKeyStore");
 keyStore.load(null);
 KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
 KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(DEFAULT_KEY_NAME,
 KeyProperties.PURPOSE_ENCRYPT |
 KeyProperties.PURPOSE_DECRYPT)
 .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
 .setUserAuthenticationRequired(true)
 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);
 keyGenerator.init(builder.build());
 keyGenerator.generateKey();
 } catch (Exception e) {
 throw new RuntimeException(e);
 }
 }
 private void initCipher() {
 try {
 SecretKey key = (SecretKey) keyStore.getKey(DEFAULT_KEY_NAME, null);
 Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
 + KeyProperties.BLOCK_MODE_CBC + "/"
 + KeyProperties.ENCRYPTION_PADDING_PKCS7);
 cipher.init(Cipher.ENCRYPT_MODE, key);
 showFingerPrintDialog(cipher);
 } catch (Exception e) {
 throw new RuntimeException(e);
 }
 }
 private void showFingerPrintDialog(Cipher cipher) {
 CancellationSignal cancel = new CancellationSignal();
 manager.authenticate(new FingerprintManager.CryptoObject(cipher), cancel, 0, new FingerprintManager.AuthenticationCallback() {
 @Override
 public void onAuthenticationError(int errorCode, CharSequence errString) {
 }
 @Override
 public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
 }
 @Override
 public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
 Toast.makeText(Main5Activity.this, "ok", Toast.LENGTH_SHORT).show();
 }
 @Override
 public void onAuthenticationFailed() {
 }
 }, null);
 }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值