編輯:關於 Android 程式設計
近期專案裡需要用到手機指紋辨識的功能,翻了不少資料後,乾脆整理成這篇文章,把整個原理與實作一次講清楚。
指紋識別是 Android 6.0 之後才新增的能力,因此使用前必須先確認使用者的系統版本是否支援。實務上,指紋辨識的應用大致可以分成兩種情境:
純本機使用:使用者在裝置上完成指紋驗證後,不需要把任何指紋資訊回傳到後端。
與後端互動:使用者在本機完成指紋驗證後,需要把相關資訊送到後端。
無論哪一種情境,指紋辨識都離不開一個加密物件(CryptoObject),而它通常由對稱加密或非對稱加密產生。兩種做法大同小異,差別主要在密鑰的產生與使用方式:純本機場景一般採用對稱加密即可;需要與後端溝通時則多半使用非對稱加密——本機用私鑰完成指紋驗證,成功後把加密資料傳給後端,後端再以公鑰解密,還原出使用者資訊。
以下先介紹對稱加密、非對稱加密與簽名的基礎觀念,再分別說明兩種實作流程。
對稱加密、非對稱加密與簽名
在正式動手之前,先把這三個概念釐清。
對稱加密:所謂「對稱」,指的是加密與解密雙方使用同一把密鑰。密鑰是控制加解密過程的指令,演算法則是一組規則,規範如何加密與解密。因此安全性不只取決於演算法本身,密鑰管理是否得當同樣關鍵。由於加解密共用一把鑰匙,如何把密鑰安全地交到解密者手上,就成了必須解決的難題。
非對稱加密:這類演算法需要兩把密鑰——公開密鑰(publickey)與私有密鑰(privatekey)。兩者成對出現:用公開密鑰加密的資料,只有對應的私有密鑰能解開;用私有密鑰加密的資料,也只有對應的公開密鑰能解開。因為加解密用的是不同密鑰,才稱為「非對稱」。其交換機密的典型流程是:甲方產生一對密鑰並公開其中一把作為公鑰;得到公鑰的乙方用它加密機密後傳回;甲方再用自己保管的私鑰解密。
簽名:在訊息後面附加一段內容,用來證明訊息沒有被竄改。一般做法是對訊息做雜湊運算得到一個 hash 值,這個過程不可逆,無法從 hash 反推原文;發送時把這個 hash 加密當作簽名,與訊息一併送出。
由此可歸納兩者的特性:
對稱加密速度快,適合本機資料與本機資料庫的加密,但安全性不及非對稱加密。常見演算法有 DES、3DES、AES、Blowfish、IDEA、RC5、RC6。
非對稱加密安全性較高,適合需要經網路傳輸的資料,但速度較慢。它廣泛應用於 SSH、HTTPS、TLS、電子憑證、電子簽章、電子身分證等場景。
指紋識別的對稱加密實作
主要流程如下:
建立密鑰
建立密鑰會牽涉到兩個類別:KeyStore 與 KeyGenerator。
KeyStore 是存放、取得密鑰(Key)的容器,取得方式如下:
try { mKeyStore = KeyStore.getInstance("AndroidKeyStore"); } catch (KeyStoreException e) { throw new RuntimeException("Failed to get an instance of KeyStore", e); } 若要產生 Key,對稱加密時需要 KeyGenerator 類別,取得方式如下:
// 對稱加密, 創建 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); } 取得 KeyGenerator 後,就能產生一把 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); } 接著用剛才的密鑰初始化 Cipher:
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); } 啟用指紋識別
真正要使用時,你會發現其實很單純,只要呼叫 FingerprintManager 的 authenticate(),系統就會回饋對應回呼:
public void authenticate(CryptoObject crypto, CancellationSignal cancel, int flags, AuthenticationCallback callback, Handler handler)
各參數說明如下:
辨識完成後,記得把 AuthenticationCallback 關掉:
public void stopListening() { if (cancellationSignal != null) { selfCancelled = true; cancellationSignal.cancel(); cancellationSignal = null; } } 覆寫回呼方法
呼叫 authenticate() 後,系統會啟動指紋感測器開始掃描,並透過下列方法回報結果:
// 成功 onAuthenticationSucceeded() // 失敗 onAuthenticationFaile() // 錯誤 onAuthenticationError()
我們一般會覆寫這幾個方法來實作自己的邏輯。至於 onAuthenticationFailed() 與 onAuthenticationError() 的差異,後面會說明。
指紋識別的非對稱加密實作
流程與前面類似:
可見兩種方式的差別主要在密鑰的產生與使用。
建立密鑰
這裡改用 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()
幾點重點:
1. 指紋辨識失敗會呼叫 onAuthenticationFailed(),此時感測器並未關閉,系統給 5 次重試機會;連續 5 次失敗後才會呼叫 onAuthenticationError()。
2. 一旦呼叫 onAuthenticationError() 或 onAuthenticationSucceeded(),感測器會關閉,必須重新授權、再次呼叫 authenticate() 才能繼續。
3. onAuthenticationError() 關閉感測器後再次呼叫 authenticate() 會有一段禁用期,長短因廠商而異,有的是 1 分鐘、有的是 30 秒。某些系統在禁用期內連其他 App 甚至系統指紋解鎖都無法使用;有些系統則可透過其他 App 或系統解鎖立即重置。
官方範例
Android Sample 中有兩份指紋範例可供參考:對稱加密為 android-FingerprintDialog;非對稱加密為 android-AsymmetricFingerprintDialog。
以上就是 Android 指紋識別的完整整理,後續我會持續補充相關內容,也感謝大家對本站的支持!
Android 5.0 多種側滑欄效果實作
普通側滑效果 常見側滑菜單可透過自定義 HorizontalScrollView 實作。核心概念是將菜單與內容放在同一個水平捲動容器中,並透過 onMeasure、onL
Android 基於 Cordova 3.3 的插件開發入門
最近工作中的項目需要用 Cordova 進行插件開發。關於 Cordova 的作用這裡就不再贅述,感興趣的同學可自行搜索。本文直接進入正題,用一個小 Demo 一步步推進
Android 滑動效果全解析:從座標系到七種實作手法
滑動效果背後的原理 Android 座標系 要取得 View 相對於螢幕的座標(也就是 View 左上角的絕對位置),可以這樣做: View view = (Vie
Android 5.1 Vold 增加 NTFS 存儲支持的移植思路
在 Android 原生存儲體系中,vold 負責管理可移動存儲與掛載流程。原生實現通常更偏向 FAT 等常見格式,而機頂盒、電視盒子等設備常需要支持 NTFS U 盤。