Skip to content Skip to sidebar Skip to footer

How To Prevent Chooseprivatekeyalias Dialog In Android App?

I have an android app that call a secured website in a webview. The webview retrieve the certificate to give it to the website. I have to use the KeyChain.choosePrivateKeyAlias(thi

Solution 1:

I'm not sure about the best way to resolve this problem, but here is what I did that worked fine for me.

I checked a boolean variable in the preferences, and if it returns false, I display the choosePrivateKeyAlias window. If it returns true, I know that I have permission to retrieve the certificate directly, so there's no need to display the popup.

booleanisGranted= prefs.getBoolean("MY_CERT", false);
if(!isGranted) {
        //Get cert and private key from internal android storeKeyChainAliasCallbackkeyChainAliasCallback=newKeyChainAliasCallback() {
            @Overridepublicvoidalias(@Nullable String s) {
                Log.d(TAG, "selected alias = " + s);
                SharedPreferences.Editoreditor= getPreferences(MODE_PRIVATE).edit();
                editor.putBoolean("MY_CERT", true);
                editor.commit();
                retriveCertsTask.execute();
            }
        };
        KeyChain.choosePrivateKeyAlias(mActivity, keyChainAliasCallback, null, null, null, -1, CERT_ALIAS);
    } else {
        // Retrieve certs an private key
        retriveCertsTask.execute();
    }
}

Hope it helps...

Solution 2:

I use the following in order to check whether or not the user has already selected the certificate:

activity?.let { it1 ->
    var selectedPrivateKey = KeyChain.getPrivateKey(it1, "keystore-test")
    if (selectedPrivateKey == null) { // if we can't access the private key then prompt for cert selection
        KeyChain.choosePrivateKeyAlias(it1, {
            Log.d("App", "Popped up KeyChain selection screen")
        }, null, null, null, "keystore-test") // this is the alias that is chosen in the popup by default
    }
}

KeyChain.getPrivateKey(it1, "keystore-test") will return null if you don't have access to the private key, meaning that the user did not select a certificate yet.

This implementation will save you from having to use SharedPreferences and also won't give you a false positive if the user deletes the certificate.

Post a Comment for "How To Prevent Chooseprivatekeyalias Dialog In Android App?"