How to prevent choosePrivateKeyAlias dialog in android app?

前端 未结 2 1094
春和景丽
春和景丽 2021-01-14 08:36

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.choos

相关标签:
2条回答
  • 2021-01-14 09:10

    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.

    0 讨论(0)
  • 2021-01-14 09:22

    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.

    boolean isGranted = prefs.getBoolean("MY_CERT", false);
    if(!isGranted) {
            //Get cert and private key from internal android store
            KeyChainAliasCallback keyChainAliasCallback = new KeyChainAliasCallback() {
                @Override
                public void alias(@Nullable String s) {
                    Log.d(TAG, "selected alias = " + s);
                    SharedPreferences.Editor editor = 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...

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题