2017-01-15 49 views
1

我在玩Fingerprint demo for Android,特別是失效情況,但需要一點幫助才能將其轉化爲值得生產的邏輯。Android指紋失效

我已經測試了應用程序,並在添加指紋之後讓initCipher因失效而失敗,但應用程序必須正在運行,並且在更改設置時生成密鑰。這是因爲演示每次應用程序啓動時都會生成一個新鍵。實際上,你不想這樣做,而是在不存在的情況下生成密鑰,如果它確實執行適當的無效化操作(無論應用程序是否正在運行),則重新生成該密鑰。

如何修改應用程序,以便每次都不生成密鑰,而是執行檢查以查看是否存在第一個存在,然後隨後加載該密鑰?您可以在刪除鑰匙失效之後再使用之前的邏輯和登記週期嗎?

回答

1

通過查看KeyStore類,並修改initCipher(),我自己找到了答案。沒有最好的實現,但不夠好,考出來的東西:

private boolean initCipher(Cipher cipher, String keyName) { 
    try { 
     mKeyStore.load(null); 
     // ADDED: Check is keystore contains my key name 
     if(!mKeyStore.containsAlias(DEFAULT_KEY_NAME)) { 
      // ADDED: Create if it doesn't 
      createKey(DEFAULT_KEY_NAME, true); 
     } 
     SecretKey key = (SecretKey) mKeyStore.getKey(keyName, null); 
     cipher.init(Cipher.ENCRYPT_MODE, key); 
     return true; 
    } catch (KeyPermanentlyInvalidatedException e) { 
     // ADDED: Remove the key if it is invalidated so 
     // it can be created fresh next time 
     try { 
      mKeyStore.deleteEntry(keyName); 
     } catch (KeyStoreException e1) { 
      e1.printStackTrace(); 
      return false; 
     } 
     return false; 
    } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException 
      | NoSuchAlgorithmException | InvalidKeyException e) { 
     throw new RuntimeException("Failed to init Cipher", e); 
    } 
} 

還需要從onCreate()刪除createKey()呼叫太明顯。