Saturday, 20 February 2021

Android keystore keys wiped regularly

I am using Android's keystore to implement fingerprint unlock of my Android app. I therefore use KeyGenerator to create a key using

            var _keyGen = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, "AndroidKeyStore")
            KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(GetAlias(_keyId),
                    KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                .SetBlockModes(KeyProperties.BlockModeCbc)
                // Require the user to authenticate with biometry to authorize every use
                // of the key
                .SetEncryptionPaddings(KeyProperties.EncryptionPaddingPkcs7)
                .SetUserAuthenticationRequired(true);
            
            _keyGen.Init(
                builder
                .Build());
            _keyGen.GenerateKey();

When I later enumerate the aliases in the store I find the key I have created:

            _keystore.Load(null);
            var aliases = _keystore.Aliases();
            if (aliases == null)
            {
                og("KS: no aliases");
            }
            else
            {
                while (aliases.HasMoreElements)
                {
                    var o = aliases.NextElement();
                    Log("alias: " + o?.ToString());
                }
            }

While this is working reliably on most devices, some devices (e.g. Google Pixel 4a) seem to "lose" the keys in the Keystore quite regularly. When enumerating the aliases as above, no key is listed anymore. I can reproduce this behavior by updating my app using a debugger (settings are such that SharedPreferences and app data are kept and I do not have this behavior on another device).

Is there anything I can do to prevent losing the keys?



from Android keystore keys wiped regularly

No comments:

Post a Comment