安卓指纹识别

转载地址:
http://blog.csdn.net/createchance/article/details/51991764


权限要求:

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

设备系统要求:
6.0以上


相关代码:

package com.example.yangjie.testfingerprint;

import android.app.KeyguardManager;
import android.os.Build;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.support.v4.os.CancellationSignal;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= 23) {
            //  获取指纹识别管理员
            FingerprintManagerCompat fingerprintManager = FingerprintManagerCompat.from(this);
            // 设备是否支持指纹识别
            if (fingerprintManager.isHardwareDetected()) {
                // 设备是否属于安全保护中(开启锁屏)
                KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
                if (keyguardManager.isKeyguardSecure()) {
                    // 设备是否已有注册过的指纹
                    if (fingerprintManager.hasEnrolledFingerprints()) {
                        // 开始验证指纹
                        CryptoObjectHelper cryptoObjectHelper = null;
                        try {
                            // 可以调用cancellationSignal.cancel()方法取消指纹验证;
                            CancellationSignal cancellationSignal = new CancellationSignal();

                            cryptoObjectHelper = new CryptoObjectHelper();
                            fingerprintManager.authenticate(cryptoObjectHelper.buildCryptoObject(), 0,
                                    cancellationSignal, authenticationCallback, null);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(this, "设备未注册指纹", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(this, "没开启锁屏保护", Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(this, "不支持指纹识别", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(this, "指纹识别只有在6.0以上的系统才支持使用", Toast.LENGTH_LONG).show();
        }
    }


    // 指纹验证的回调函数
    FingerprintManagerCompat.AuthenticationCallback authenticationCallback = new FingerprintManagerCompat.AuthenticationCallback() {
        @Override
        public void onAuthenticationError(int errMsgId, CharSequence errString) {
            super.onAuthenticationError(errMsgId, errString);
            Toast.makeText(MainActivity.this, "errMsgId = "+errMsgId+" + errString = "+errString, Toast.LENGTH_LONG).show();
            Log.d("MyTAG", "errMsgId = "+errMsgId+" + errString = "+errString);
        }

        @Override
        public void onAuthenticationFailed() {
            super.onAuthenticationFailed();
            Toast.makeText(MainActivity.this, "fail", Toast.LENGTH_LONG).show();
            Log.d("MyTAG", "fail");

        }

        @Override
        public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
            super.onAuthenticationHelp(helpMsgId, helpString);
            Toast.makeText(MainActivity.this, "helpMsgId = "+helpMsgId+" + helpString = "+helpString, Toast.LENGTH_LONG).show();
            Log.d("MyTAG", "helpMsgId = "+helpMsgId+" + helpString = "+helpString);
        }

        @Override
        public void onAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result) {
            super.onAuthenticationSucceeded(result);
            Toast.makeText(MainActivity.this, "result = "+result, Toast.LENGTH_LONG).show();
            Log.d("MyTAG", "result = "+result);

            // 验证Cipher对象
            try {
                result.getCryptoObject().getCipher().doFinal();
                // 如果没有发生异常,证明指纹验证成功!
                Toast.makeText(MainActivity.this, "指纹验证成功!", Toast.LENGTH_LONG).show();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "指纹验证失败!", Toast.LENGTH_LONG).show();
            } catch (BadPaddingException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "指纹验证失败!", Toast.LENGTH_LONG).show();
            }
        }
    };

}

CryptoObjectHelper

package com.example.yangjie.testfingerprint;

import android.annotation.TargetApi;
import android.os.Build;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore.KeyProperties;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;

import java.security.Key;
import java.security.KeyStore;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

/**
 * Created by yangjie on 2017/12/8.
 */

public class CryptoObjectHelper
{
    // This can be key name you want. Should be unique for the app.
    static final String KEY_NAME = "com.createchance.android.sample.fingerprint_authentication_key";

    // We always use this keystore on Android.
    static final String KEYSTORE_NAME = "AndroidKeyStore";

    // Should be no need to change these values.
    static final String KEY_ALGORITHM = KeyProperties.KEY_ALGORITHM_AES;
    static final String BLOCK_MODE = KeyProperties.BLOCK_MODE_CBC;
    static final String ENCRYPTION_PADDING = KeyProperties.ENCRYPTION_PADDING_PKCS7;
    static final String TRANSFORMATION = KEY_ALGORITHM + "/" +
            BLOCK_MODE + "/" +
            ENCRYPTION_PADDING;
    final KeyStore _keystore;

    public CryptoObjectHelper() throws Exception
    {
        _keystore = KeyStore.getInstance(KEYSTORE_NAME);
        _keystore.load(null);
    }

    public FingerprintManagerCompat.CryptoObject buildCryptoObject() throws Exception
    {
        Cipher cipher = createCipher(true);
        return new FingerprintManagerCompat.CryptoObject(cipher);
    }

    @TargetApi(Build.VERSION_CODES.M)
    Cipher createCipher(boolean retry) throws Exception
    {
        Key key = GetKey();
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        try
        {
            cipher.init(Cipher.ENCRYPT_MODE | Cipher.DECRYPT_MODE, key);
        } catch(KeyPermanentlyInvalidatedException e)
        {
            _keystore.deleteEntry(KEY_NAME);
            if(retry)
            {
                createCipher(false);
            } else
            {
                throw new Exception("Could not create the cipher for fingerprint authentication.", e);
            }
        }
        return cipher;
    }

    Key GetKey() throws Exception
    {
        Key secretKey;
        if(!_keystore.isKeyEntry(KEY_NAME))
        {
            CreateKey();
        }

        secretKey = _keystore.getKey(KEY_NAME, null);
        return secretKey;
    }

    @TargetApi(Build.VERSION_CODES.M)
    void CreateKey() throws Exception
    {
        KeyGenerator keyGen = KeyGenerator.getInstance(KEY_ALGORITHM, KEYSTORE_NAME);
        KeyGenParameterSpec keyGenSpec =
                new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                        .setBlockModes(BLOCK_MODE)
                        .setEncryptionPaddings(ENCRYPTION_PADDING)
                        .setUserAuthenticationRequired(true)
                        .build();
        keyGen.init(keyGenSpec);
        keyGen.generateKey();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值