1. 程式人生 > >android指紋識別認證實現

android指紋識別認證實現

erp ica signal except mpat too adding return parent

Android從6.0系統支持指紋認證功能

啟動頁面簡單實現

package com.loaderman.samplecollect.zhiwen;

import android.annotation.TargetApi;
import android.app.FragmentManager;
import android.app.KeyguardManager;
import android.content.Intent;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.loaderman.samplecollect.R; import java.security.KeyStore; import javax.crypto.Cipher;
import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; public class GoActivity extends AppCompatActivity { private static final String DEFAULT_KEY_NAME = "default_key"; KeyStore keyStore; private FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_go); if (supportFingerprint()) { initKey(); initCipher(); } } public boolean supportFingerprint() { if (Build.VERSION.SDK_INT < 23) { Toast.makeText(this, "您的系統版本過低,不支持指紋功能", Toast.LENGTH_SHORT).show(); return false; } else { KeyguardManager keyguardManager = getSystemService(KeyguardManager.class); FingerprintManager fingerprintManager = getSystemService(FingerprintManager.class); if (!fingerprintManager.isHardwareDetected()) { Toast.makeText(this, "您的手機不支持指紋功能", Toast.LENGTH_SHORT).show(); return false; } else if (!keyguardManager.isKeyguardSecure()) { Toast.makeText(this, "您還未設置鎖屏,請先設置鎖屏並添加一個指紋", Toast.LENGTH_SHORT).show(); return false; } else if (!fingerprintManager.hasEnrolledFingerprints()) { Toast.makeText(this, "您至少需要在系統設置中添加一個指紋", Toast.LENGTH_SHORT).show(); return false; } } return true; } @TargetApi(23) 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); } } @TargetApi(23) 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) { FingerprintDialogFragment fragment = new FingerprintDialogFragment(); fragment.setCipher(cipher); fragmentManager = getFragmentManager(); fragment.show(fragmentManager,""); } public void onAuthenticated() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } }

指紋認證頁面:

package com.loaderman.samplecollect.zhiwen;

import android.annotation.TargetApi;
import android.app.DialogFragment;
import android.content.Context;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.support.annotation.Nullable;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.loaderman.samplecollect.R;

import javax.crypto.Cipher;

@TargetApi(23)
public class FingerprintDialogFragment extends DialogFragment {
    private FingerprintManager fingerprintManager;
    private CancellationSignal mCancellationSignal;
    private Cipher mCipher;
    private GoActivity mActivity;
    private TextView errorMsg;
    /**
     * 標識是否是用戶主動取消的認證。
     */
    private boolean isSelfCancelled;

    public void setCipher(Cipher cipher) {
        mCipher = cipher;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (GoActivity) getActivity();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fingerprintManager = getContext().getSystemService(FingerprintManager.class);
        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Material_Light_Dialog);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fingerprint_dialog, container, false);
        errorMsg = v.findViewById(R.id.error_msg);
        TextView cancel = v.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                stopListening();
            }
        });
        return v;
    }

    @Override
    public void onResume() {
        super.onResume(); // 開始指紋認證監聽
        startListening(mCipher);
    }

    @Override
    public void onPause() {
        super.onPause(); // 停止指紋認證監聽
        stopListening();
    }

    private void startListening(Cipher cipher) {
        isSelfCancelled = false;
        mCancellationSignal = new CancellationSignal();
        fingerprintManager.authenticate(new FingerprintManager.CryptoObject(cipher), mCancellationSignal, 0, new FingerprintManager.AuthenticationCallback() {
            @Override
            public void onAuthenticationError(int errorCode, CharSequence errString) {
                if (!isSelfCancelled) {
                    errorMsg.setText(errString);
                    if (errorCode == FingerprintManager.FINGERPRINT_ERROR_LOCKOUT) {
                        Toast.makeText(mActivity, errString, Toast.LENGTH_SHORT).show();
                        dismiss();
                    }
                }
            }

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

            @Override
            public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
                Toast.makeText(mActivity, "指紋認證成功", Toast.LENGTH_SHORT).show();
                mActivity.onAuthenticated();
            }

            @Override
            public void onAuthenticationFailed() {
                errorMsg.setText("指紋認證失敗,請再試一次");
            }
        }, null);
    }

    private void stopListening() {
        if (mCancellationSignal != null) {
            mCancellationSignal.cancel();
            mCancellationSignal = null;
            isSelfCancelled = true;
        }
    }
}

認證布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginTop="15dp"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/ic_zhiwen" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:text="請驗證指紋解鎖"
        android:textColor="#000"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/error_msg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="5dp"
        android:maxLines="1"
        android:textColor="#f45"
        android:textSize="12sp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:layout_marginTop="10dp"
        android:background="#ccc" />

    <TextView
        android:id="@+id/cancel"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:text="取消"
        android:textColor="#5d7883"
        android:textSize="16sp" />
</LinearLayout>

認證成功後進入主頁面

android指紋識別認證實現