Rohan Patel
Rohan Patel

Reputation: 1858

How to resolve KeyStoreConnectException on Android 10?

My app is working pretty well on all the Android OS except Android 10. I am using the Motorola One Power device which got updated with Android 10. We are using Android Keystore to encrypt databases.

App is getting crash on luanch with below error.

android.security.keystore.KeyStoreConnectException: Failed to communicate with keystore service at android.security.keystore.AndroidKeyStoreCipherSpiBase.ensureKeystoreOperationInitialized(AndroidKeyStoreCipherSpiBase.java:256) at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineInit(AndroidKeyStoreCipherSpiBase.java:148) at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:2980)

Its a KeyStoreConnectException issue. The app is taking time to connect to KeyStoreConnectException.

Note: If I run the app in debugged mode then it's working fine.

Please help me to find solution. Thanks in advance.

Upvotes: 7

Views: 2049

Answers (3)

georgiptr
georgiptr

Reputation: 141

As MatPag pointed out, this is a known bug in Android 10 that's not present in earlier or later versions. As I call Cipher::init() in several places, here is a convenient wrapper function in Kotlin:

private fun keyStoreWorkaroundForAndroid10(f: () -> Unit) {
    for (i in 0..3) {
        try {
            f()
            return
        } catch (e: ProviderException) {
            Timber.d("Applying Android 10 KeyStoreConnectException bug workaround. Counter: ${i}, Exception: ${e.message}")
            Thread.sleep(100)
            continue
        }
    }
}

And then you call it like this (remember - in a background thread):

keyStoreWorkaroundForAndroid10 {
    cipherEncrypt.init(Cipher.ENCRYPT_MODE, publicKey)
}

Upvotes: 4

MatPag
MatPag

Reputation: 44813

This is a known bug tracked here https://issuetracker.google.com/issues/147384380

Google fixed it and probably will be available in Android 11.

We currently don't know if it will be fixed with security patches on Android 10 at some point

Upvotes: 0

kevin.xu
kevin.xu

Reputation: 29

I think your code run takes long time, you can move to the thread, try it!

Upvotes: -1

Related Questions