Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 指紋識別 Demo 開發實例:從加密概念到完整流程

編輯:關於 Android 程式設計

指紋識別是 Android 6.0 之後才加入的功能,使用前必須先判斷使用者機型的系統版本是否支援。實務上,指紋辨識主要分成兩種情境:

純本機使用:使用者在本機完成指紋驗證後,不需把指紋相關資訊傳到後端。

與後端互動:使用者在本機完成驗證後,需要把相關資訊送到後端。由於指紋功能需要一個加密物件(CryptoObject),而它通常由對稱或非對稱加密產生,因此兩種情境的差別主要在密鑰的建立與使用:純本機一般用對稱加密即可;與後端互動則多半用非對稱加密——本機以私鑰完成驗證,成功後把加密資訊傳給後端,後端再用公鑰解密取得使用者資訊。

以下先介紹對稱加密、非對稱加密與簽名的觀念,再分別說明兩種實作。

對稱加密、非對稱加密與簽名

對稱加密:加密與解密雙方使用同一把密鑰。密鑰是控制加解密過程的指令,演算法是一組規則,規範如何加解密。因此安全性不只取決於演算法,密鑰管理同樣重要;由於加解密共用一把鑰匙,如何安全地把密鑰交到解密者手上,是必須解決的問題。

非對稱加密:需要兩把密鑰——公開密鑰(publickey)與私有密鑰(privatekey)。兩者成對:公鑰加密的資料只有對應私鑰能解,私鑰加密的資料只有對應公鑰能解。典型流程是甲方產生一對密鑰並公開公鑰,乙方用公鑰加密機密後傳回,甲方再用私鑰解密。

簽名:在訊息後附加一段內容以證明訊息未被竄改。一般做法是對訊息做不可逆的 hash 運算得到 hash 值,發送時把 hash 加密當作簽名,與訊息一併送出。

由此可歸納:

對稱加密速度快,適合本機資料與本機資料庫加密,安全性不及非對稱加密。常見演算法有 DES、3DES、AES、Blowfish、IDEA、RC5、RC6。

非對稱加密安全性較高,適合需經網路傳輸的資料,但速度較慢,廣泛應用於 SSH、HTTPS、TLS、電子憑證、電子簽章、電子身分證等。

指紋識別的對稱加密實作

主要流程:用 KeyGenerator 建立對稱密鑰並存進 KeyStore;把 setUserAuthenticationRequired() 設為 true;用密鑰初始化 Cipher 並呼叫 FingerprintManager.authenticate() 啟動監聽;最後覆寫 AuthenticationCallback 的幾個回呼,處理成功與失敗等狀況。

建立密鑰

建立密鑰會用到 KeyStore 與 KeyGenerator。KeyStore 是存放、取得密鑰的容器:

 try { mKeyStore = KeyStore.getInstance("AndroidKeyStore"); } catch (KeyStoreException e) { throw new RuntimeException("Failed to get an instance of KeyStore", e); }

對稱加密時用 KeyGenerator 產生 Key:

 // 對稱加密, 創建 KeyGenerator 對象 try { mKeyGenerator = KeyGenerator .getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new RuntimeException("Failed to get an instance of KeyGenerator", e); }

取得物件後即可產生 Key:

 try { keyStore.load(null); KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(defaultKeyName, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setUserAuthenticationRequired(true) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { builder.setInvalidatedByBiometricEnrollment(true); } keyGenerator.init(builder.build()); keyGenerator.generateKey(); } catch (CertificateException | NoSuchAlgorithmException | IOException | InvalidAlgorithmParameterException e) { e.printStackTrace(); }

建立並初始化 Cipher 物件

Cipher 依特定加密規則處理資料,是呼叫指紋功能時的必要角色:

 Cipher defaultCipher; try { defaultCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { throw new RuntimeException("創建Cipher對象失敗", e); }

接著用剛才的密鑰初始化:

 try { keyStore.load(null); SecretKey key = (SecretKey) keyStore.getKey(keyName, null); cipher.init(Cipher.ENCRYPT_MODE, key); return true; } catch (IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | KeyStoreException | InvalidKeyException e) { throw new RuntimeException("初始化 cipher 失敗", e); }

啟用指紋識別

真正使用時其實很單純,只要呼叫 authenticate(),系統便會回饋回呼:

 public void authenticate(CryptoObject crypto, CancellationSignal cancel, int flags, AuthenticationCallback callback, Handler handler)

參數說明:

第一個是加密物件,用 new FingerprintManager.CryptoObject(cipher) 由 Cipher 包裝而成。

第二個是 CancellationSignal,提供取消能力,new CancellationSignal() 即可。

第三個是旗標,預設為 0。

第四個是 AuthenticationCallback,它是 FingerprintManager 內部的抽象類別,提供成功、失敗等回呼,需要覆寫。最後一個 Handler 用於處理回呼事件,可傳 null。

辨識完成後,記得關掉 AuthenticationCallback:

 public void stopListening() { if (cancellationSignal != null) { selfCancelled = true; cancellationSignal.cancel(); cancellationSignal = null; } }

覆寫回呼方法

呼叫 authenticate() 後,系統會啟動感測器掃描,並透過下列方法回報:

 // 成功 onAuthenticationSucceeded() // 失敗 onAuthenticationFaile() // 錯誤 onAuthenticationError()

我們一般會覆寫這幾個方法實作功能。至於 onAuthenticationFailed() 與 onAuthenticationError() 的差異,後面說明。

指紋識別的非對稱加密實作

流程與前面類似:用 KeyPairGenerator 建立一組非對稱密鑰;用私鑰簽名並以簽名建立加密物件,作為 authenticate() 的參數啟動監聽;最後覆寫 AuthenticationCallback 的幾個回呼。可見兩種方式最明顯的差別在於密鑰的產生與使用。

建立密鑰

這裡用 KeyPairGenerator 建立非對稱密鑰,先取得物件:

 // 非對稱加密,創建 KeyPairGenerator 對象 try { mKeyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore"); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new RuntimeException("Failed to get an instance of KeyPairGenerator", e); }

取得後即可建立 KeyPair:

 try { // Set the alias of the entry in Android KeyStore where the key will appear // and the constrains (purposes) in the constructor of the Builder mKeyPairGenerator.initialize( new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_SIGN) .setDigests(KeyProperties.DIGEST_SHA256) .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1")) // Require the user to authenticate with a fingerprint to authorize // every use of the private key .setUserAuthenticationRequired(true) .build()); mKeyPairGenerator.generateKeyPair(); } catch (InvalidAlgorithmParameterException e) { throw new RuntimeException(e); }

簽名

對稱加密用 Cipher 建立 CryptoObject,這裡則改用私鑰簽名,再以簽名物件建立 CryptoObject:

 // 使用私鑰簽名 try { mKeyStore.load(null); PrivateKey key = (PrivateKey) mKeyStore.getKey(KEY_NAME, null); mSignature.initSign(key); return true; } catch (KeyPermanentlyInvalidatedException e) { return false; } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException("Failed to init Cipher", e); }

同樣以 new FingerprintManager.CryptoObject(mSignature) 建立 CryptoObject。

呼叫指紋識別

呼叫方式與對稱加密相同,都是 FingerprintManager.authenticate(),此處不再重複。

監聽回呼

監聽回呼也類似,唯一不同的是成功後需與後端互動,也就是 onAuthenticationSucceeded() 內的邏輯不同。

實務上的注意事項

判斷使用者能否使用指紋功能

為了安全,通常要求使用者先開啟密碼鎖屏,且至少錄入一枚指紋:

 // 如果沒有設置密碼鎖屏,則不能使用指紋識別 if (!keyguardManager.isKeyguardSecure()) { Toast.makeText(this, "請在設置界面開啟密碼鎖屏功能", Toast.LENGTH_LONG).show(); } // 如果沒有錄入指紋,則不能使用指紋識別 if (!fingerprintManager.hasEnrolledFingerprints()) { Toast.makeText(this, "您還沒有錄入指紋, 請在設置界面錄入至少一個指紋", Toast.LENGTH_LONG).show(); }

這裡用到 KeyguardManager(螢幕保護相關)與 FingerprintManager(指紋核心類別)。

關於指紋識別回呼方法

開發中常用的三個回呼:

 onAuthenticationError() onAuthenticationSucceeded() onAuthenticationFailed()

幾點重點:

當指紋辨識失敗會呼叫 onAuthenticationFailed(),此時感測器未關閉,系統給 5 次重試機會;連續 5 次失敗後才會呼叫 onAuthenticationError()。

一旦呼叫 onAuthenticationError() 或 onAuthenticationSucceeded(),感測器會關閉,必須重新授權、再次呼叫 authenticate() 才能繼續。

onAuthenticationError() 關閉感測器後再次呼叫 authenticate() 會有一段禁用期,長短因廠商而異,有的是 1 分鐘、有的是 30 秒。某些系統在禁用期內連其他 App 甚至系統指紋解鎖都無法使用;有些系統則可透過其他 App 或系統解鎖立即重置。

以上就是 Android 指紋識別 Demo 開發實例的整理,希望對大家有所幫助。若有疑問歡迎留言,我會盡快回覆。也感謝大家對本站的支持!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved