14

I am trying to use masterKey to encrypt shared prefs. However, sometimes my users are crashing due to invalidKeyException from keystore. I cannot reproduce this locally =\

 java.security.KeyStoreException: the master key android-keystore://_androidx_security_master_key_ exists but is unusable


 Caused by: java.security.InvalidKeyException: Keystore cannot load the key with ID: _androidx_security_master_key_

Any ideas why this is happening?

    val masterKey = MasterKey.Builder(context)
        .setKeyGenParameterSpec(
            KeyGenParameterSpec.Builder(
                MasterKey.DEFAULT_MASTER_KEY_ALIAS,
                PURPOSE_ENCRYPT or PURPOSE_DECRYPT
            )
                .setBlockModes(BLOCK_MODE_GCM)
                .setEncryptionPaddings(ENCRYPTION_PADDING_NONE)
                .setKeySize(MasterKey.DEFAULT_AES_GCM_MASTER_KEY_SIZE)
                .build()
        )
        .build()
    securePrefs = EncryptedSharedPreferences.create(
        context,
        PREFERENCES,
        masterKey,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    )
8
  • 2
    Did you solve this issue? Any clue why this occurs? Dec 24, 2020 at 7:51
  • 1
    I was able to repro once when I wiped the simulator data and re-ran app. However, not able to repro 100%. No solution currently.
    – Mocha
    Dec 25, 2020 at 9:02
  • 1
    Wipe the emulator? but then why should it occur? Do you keep seeing this issue for users? Maybe it's on custom ROMs? Dec 25, 2020 at 23:02
  • 1
    Yeah, we think it has to due with a cached user prefs / master key or something... We don't have ROMs logged. Maybe we'll look into that.
    – Mocha
    Dec 27, 2020 at 3:26
  • 2
    See github.com/google/tink/issues/535#issuecomment-912170221 for potential workarounds, I can confirm that this is still happening with the stable version as well Mar 22, 2022 at 9:10

2 Answers 2

10

The issue has been in detail reported to the Google bug tracker as well. Might be better to follow the discussions there.

https://issuetracker.google.com/issues/176215143

1

You can see Android issue here: https://issuetracker.google.com/issues/176215143?pli=1

I can suggest simple workaround with removing the data of preferences and key from a system KeyStore. With this fix after the reinstall your App can't restore the data. But at least your App could start from fresh page without crash. You could create some custom builder and use it to create the Encrypted Preferences:

class EncryptedPreferenceBuilder(val context: Context) {


companion object {
    private const val TAG = "EncryptedPreferenceBuilder"
    private const val KEYSTORE_PROVIDER = "AndroidKeyStore"
}

private val masterKeyAlias = MasterKey.Builder(context, MasterKey.DEFAULT_MASTER_KEY_ALIAS).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build()

fun build(prefName: String): SharedPreferences {
    return try {
        createSharedPreferences(prefName)
    } catch (e: Exception) {
        Log.e(TAG, "Error occurred while create shared preference")
        deleteSharedPreferences(prefName)
        deleteMasterKey()
        createSharedPreferences(prefName)
    }
}

private fun createSharedPreferences(prefName: String) = EncryptedSharedPreferences.create(
    context,
    prefName,
    masterKeyAlias,
    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)

private fun clearSharedPreference(prefName: String) {
    context.getSharedPreferences(prefName, Context.MODE_PRIVATE).edit().clear().apply()
}

private fun deleteSharedPreferences(prefName: String) {
    try {
        clearSharedPreference(prefName)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            context.deleteSharedPreferences(prefName)
        } else {
            FileUtils.delete("${context.filesDir.parent}/shared_prefs/$prefName.xml")
        }
    } catch (e: Exception) {
        Log.e(TAG, "Error delete preferences")
    }
}

private fun deleteMasterKey() {
    try {
        val keyStore = KeyStore.getInstance(KEYSTORE_PROVIDER)
        keyStore.load(null)
        keyStore.deleteEntry(MasterKey.DEFAULT_MASTER_KEY_ALIAS)
    } catch (e: Exception) {
        Log.e(TAG, "Error delete MasterKey")
    }
}
}

Usage:

val prefs = EncryptedSharedPreferenceBuilder(context).build("APP_PREFS_NAME")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.