安卓指紋認證使用智能手機觸摸傳感器對用戶進行身份驗證。Android Marshmallow(棉花糖)提供了一套API,使用戶很容易使用觸摸傳感器。在Android Marshmallow以前訪問觸摸傳感器的方法不是標準的。html
本文地址:http://wuyudong.com/2016/12/15/3146.html,轉載請註明出處。java
使用安卓指紋認證有幾個好處:android
一、更快更容易使用api
二、安全:指紋能夠識別你的身份惟一安全
三、在線交易更加的容易app
在使用android指紋識別以前你必須遵循一些步驟,可能看起來真的很複雜,但本文將教你你一步一步實現。ide
結果就像下圖顯示的那樣:post
![](http://static.javashuo.com/static/loading.gif)
開始 Android 指紋認證
就如上面所說,指紋認證過程有如下幾個步驟:測試
- 驗證鎖屏是不是安全的,或者換句話說,它是用密碼或模式保護的
- 確認在智能手機上已經有一個指紋是註冊的
- 訪問 Android keystore 存儲將對象加密/解密的密鑰
- 生成一個加密密鑰和密碼
- 啓動認證過程
- 實現一個回調類來處理身份認證事件
就是這些了,下面來實現上面的步驟!ui
在開始的時候,先得開啓觸摸傳感器與身份認證的權限,在清單文件 Manifest.xml 中添加:
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
如今是時候建立main activity 類來處理全部的認證步驟了.
驗證Android安全鎖屏
第一步是確認鎖屏是不是安全的,這個可使用 KeyguardManager 和FingerprintManager 來解決。 咱們能夠經過使用 getSystemService 類獲取它們的實例:
// Keyguard Manager
KeyguardManager keyguardManager = (KeyguardManager)
getSystemService(KEYGUARD_SERVICE);
// Fingerprint Manager
fingerprintManager = (FingerprintManager)
getSystemService(FINGERPRINT_SERVICE);
如今,咱們的認證應用能夠檢查是否全部的安全判斷都知足:
private boolean checkFinger() {
// Keyguard Manager
KeyguardManager keyguardManager = (KeyguardManager)
getSystemService(KEYGUARD_SERVICE);
// Fingerprint Manager
fingerprintManager = (FingerprintManager)
getSystemService(FINGERPRINT_SERVICE);
try {
// Check if the fingerprint sensor is present
if (!fingerprintManager.isHardwareDetected()) {
// Update the UI with a message
message.setText("Fingerprint authentication not supported");
return false;
}
if (!fingerprintManager.hasEnrolledFingerprints()) {
message.setText("No fingerprint configured.");
return false;
}
if (!keyguardManager.isKeyguardSecure()) {
message.setText("Secure lock screen not enabled");
return false;
}
}
catch(SecurityException se) {
se.printStackTrace();
}
return true;
}
注意到應用程序驗證了至少有一個指紋已經註冊不然認證過程將不會開始,下面的圖片展現了若是沒有發現註冊指紋提示一個錯誤信息
![](http://static.javashuo.com/static/loading.gif)
若是一切就緒,一切判斷狀況都知足,認證應用產生密鑰並訪問Android store.
![](http://static.javashuo.com/static/loading.gif)
訪問Android keystore並生成密鑰
接下來的步驟就是訪問Android keystore 併產生密鑰來加密數據,應用程序在一個叫 generateKey() 的方法中單獨完成.
// Get the reference to the key store
keyStore = KeyStore.getInstance("AndroidKeyStore");
接着必須得到密鑰生成器的引用:
// Key generator to generate the key
keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,
"AndroidKeyStore");
最後,咱們必須初始化密鑰生成器:
keyGenerator.init( new
KeyGenParameterSpec.Builder(KEY_NAME,
KeyProperties.PURPOSE_ENCRYPT |
KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(
KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
keyGenerator.generateKey();
注意到咱們特別指出密鑰的使用: 加密和解密而且認證須要使用密鑰,最後應用程序生成了密鑰 (最後一行).
上面的代碼完整的方法以下:
private void generateKey() throws FingerprintException {
try {
// Get the reference to the key store
keyStore = KeyStore.getInstance("AndroidKeyStore");
// Key generator to generate the key
keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,
"AndroidKeyStore");
keyStore.load(null);
keyGenerator.init( new
KeyGenParameterSpec.Builder(KEY_NAME,
KeyProperties.PURPOSE_ENCRYPT |
KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(
KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
keyGenerator.generateKey();
}
catch(KeyStoreException
| NoSuchAlgorithmException
| NoSuchProviderException
| InvalidAlgorithmParameterException
| CertificateException
| IOException exc) {
exc.printStackTrace();
throw new FingerprintException(exc);
}
}
建立Android Cipher
一旦密鑰準備好了,最後步驟就是使用以前生成的密鑰來建立Android Cipher ,代碼很簡單:
private Cipher generateCipher() throws FingerprintException {
try {
Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
+ KeyProperties.BLOCK_MODE_CBC + "/"
+ KeyProperties.ENCRYPTION_PADDING_PKCS7);
SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME,
null);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher;
}
catch (NoSuchAlgorithmException
| NoSuchPaddingException
| InvalidKeyException
| UnrecoverableKeyException
| KeyStoreException exc) {
exc.printStackTrace();
throw new FingerprintException(exc);
}
}
構建 Android 指紋認證 app
是時候將前面的方法組合起來建立咱們的 Android 指紋識別app,這個app很簡單隻有一個 MainClass
調用上面所示的方法開始認證處理.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
message = (TextView) findViewById(R.id.fingerStatus);
Button btn = (Button) findViewById(R.id.authBtn);
final FingerprintHandler fph = new FingerprintHandler(message);
if (!checkFinger()) {
btn.setEnabled(false);
}
else {
// We are ready to set up the cipher and the key
try {
generateKey();
Cipher cipher = generateCipher();
cryptoObject =
new FingerprintManager.CryptoObject(cipher);
}
catch(FingerprintException fpe) {
// Handle exception
btn.setEnabled(false);
}
}
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
message.setText("Swipe your finger");
fph.doAuth(fingerprintManager, cryptoObject);
}
});
}
有幾點須要注意的,首先,Android app 建立一個 CryptoObject
對象來處理認證過程,接着,app 一個button,當用戶點擊它的時候認證過程開始,當上面的初始化判斷條件不知足的時候這個 button 被隱藏。須要注意的最重要的事情是新類調用FingerprintHandler
. 這個類是個接收認證處理事件的回調類,此外, 此類啓動認證過程的doauth方法.
Android 指紋認證回調
最後一步是建立一個回調類,這樣咱們能夠接收事件消息並可以知道何時認證成功或者除了一些問題,這個類繼承自 FingerprintManager.AuthenticationCallback.
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private TextView tv;
public FingerprintHandler(TextView tv) {
this.tv = tv;
}
@Override
public void onAuthenticationError(int errorCode, CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
tv.setText("Auth error");
}
@Override
public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
super.onAuthenticationHelp(helpCode, helpString);
}
@Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
tv.setText("auth ok");
tv.setTextColor(tv.getContext().getResources().
getColor(android.R.color.holo_green_light));
}
@Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
}
public void doAuth(FingerprintManager manager,
FingerprintManager.CryptoObject obj) {
CancellationSignal signal = new CancellationSignal();
try {
manager.authenticate(obj, signal, 0, this, null);
}
catch(SecurityException sce) {}
}
}
有一些重要的方法須要注意,首先,doAuth 開啓認證處理,這個方法包含 CryptoObject 對象,一個取消信號和回調監聽器。下面的圖片顯示了app 的響應動做:
![](http://static.javashuo.com/static/loading.gif)
這種狀況下,用戶使用android指紋認證完成了認證。
如何在模擬器上面測試這個app?
要測試這個app,若是有可能使用具備傳感器的真機來進行,然而你還能夠在模擬器上進行測試app,在使用app以前,你必須配置igure the fingerprint accessing to the Security menu. 當系統要求你的指紋的時候你必須使用adb 命令模擬指紋接觸:
adb -e emu finger touch id(like 1,2, ecc.)
最後,當你的指紋搞定,你將獲得下面的提示:
![](http://static.javashuo.com/static/loading.gif)
最後但願你掌握了android 的指紋識別 api 並知道怎樣開發一款指紋識別 app 例子,enjoy ![:)](http://static.javashuo.com/static/loading.gif)