'How to make the secret key stored in AndroidKeyStore still exist after the user clears the data in the settings?

I use the following code to store the key to keystore

Certificate cer2 = CertificateFactory.getInstance("X.509")
                    .generateCertificate(context.getAssets().open("rsa_test.cer"));

            Certificate cer1 = CertificateFactory.getInstance("X.509")
                    .generateCertificate(context.getAssets().open("rsa_public_key.crt"));

            PrivateKey privateKey = getPrivateKey(context);   // RSA private key
            Certificate[] certChain = new Certificate[]{cer1, cer2}; // Certificate chain with the first certificate
            // containing the corresponding RSA public key.

            keyStore.setEntry(
                    alias,
                    new KeyStore.PrivateKeyEntry(privateKey, certChain),
                    new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
                            .setDigests(KeyProperties.DIGEST_SHA256)
                            .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
                            .setUserAuthenticationRequired(false)
                            .setUserAuthenticationValidityDurationSeconds(10 * 60)
                            .build());

Use this method to get the key alias

    public Enumeration<String> getAliases() {
        if (keyStore == null) {
            return null;
        }

        try {
            return keyStore.aliases();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }

        return null;
    }

How to make the secret key stored in AndroidKeyStore still exist after the user clears the data in the settings? I use the following code to store the key to keystore. Use this method to get the key alias. But I went to the setting of the device, after clearing the app data, all the Alias disappeared. Is there any way to keep the Alias from disappearing?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source