В моем приложении для Android я вставляю элемент в KeyStore, и иногда я получаю сбой, связанный с InvalidKeyException: Keystore operation failed
/ KeyStoreException: Key not found
.Обычно операция проходит успешно, но общий процент отказов составляет около 10%.Я думаю, что это, возможно, состояние гонки, когда cipher.init будет происходить до завершения создания ключа, но я не уверен.Любые идеи о том, почему этот код только иногда терпит неудачу или как решить?
Ниже приведена ошибка:
java.lang.Error: java.security.InvalidKeyException: Keystore operation failed
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1173)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.security.InvalidKeyException: Keystore operation failed
at android.security.KeyStore.getInvalidKeyException(KeyStore.java:901)
at android.security.KeyStore.getInvalidKeyException(KeyStore.java:926)
at android.security.keystore.KeyStoreCryptoOperationUtils.getInvalidKeyExceptionForInit(KeyStoreCryptoOperationUtils.java:54)
at android.security.keystore.KeyStoreCryptoOperationUtils.getExceptionForCipherInit(KeyStoreCryptoOperationUtils.java:89)
at android.security.keystore.AndroidKeyStoreCipherSpiBase.ensureKeystoreOperationInitialized(AndroidKeyStoreCipherSpiBase.java:265)
at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineInit(AndroidKeyStoreCipherSpiBase.java:109)
at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:2984)
at javax.crypto.Cipher.tryCombinations(Cipher.java:2891)
at javax.crypto.Cipher$SpiAndProviderUpdater.updateAndGetSpiAndProvider(Cipher.java:2796)
at javax.crypto.Cipher.chooseProvider(Cipher.java:773)
at javax.crypto.Cipher.init(Cipher.java:1143)
at javax.crypto.Cipher.init(Cipher.java:1084)
at com.myapp.service.KeyStoreService.createKeysAndEncrypt(KeyStoreService.kt:32)
at com.myapp.provision.ProvisionPresenter.createKeysAndEncrypt(ProvisionRepository.kt:26)
at com.myapp.provision.ProvisionPresenter.certRetrieved(ProvisionPresenter.kt:106)
at com.myapp.provision.ProvisionPresenter.access$certRetrieved(ProvisionPresenter.kt:17)
at com.myapp.provision.ProvisionPresenter$postCompleted$1.invoke(ProvisionPresenter.kt:88)
at com.myapp.provision.ProvisionPresenter$postCompleted$1.invoke(ProvisionPresenter.kt:17)
at com.myapp.service.NetworkingService$getData$1.onResponse(NetworkingService.kt:110)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:153)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: android.security.KeyStoreException: Key not found
at android.security.KeyStore.getKeyStoreException(KeyStore.java:821)
А вот мой код:
val keyGenerator = KeyGenerator
.getInstance(KeyProperties.KEY_ALGORITHM_AES, context.resources.getString(R.string.key_store_instance))
val keyGenParameterSpec = KeyGenParameterSpec.Builder(alias,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build()
keyGenerator.init(keyGenParameterSpec)
val secretKey = keyGenerator.generateKey()
val cipher = Cipher.getInstance(context.resources.getString(R.string.key_store_transformation))
//This is where the crash occurs
cipher.init(Cipher.ENCRYPT_MODE, secretKey)
val iv = cipher.iv
val byteCert = cert.toByteArray()
val encryption = cipher.doFinal(byteCert)