2017-01-15 48 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()呼叫太明显。