Kannan_SJD
Kannan_SJD

Reputation: 1062

How to retrieve installed X509 certificate from Android keychain?

I installed a X509 certificate into andorid keychain using following code:

        Intent installIntent = KeyChain.createInstallIntent();
        installIntent.putExtra(KeyChain.EXTRA_NAME, "My certificate");
        installIntent.putExtra(KeyChain.EXTRA_CERTIFICATE, certificate.getEncoded());
        startActivityForResult(installIntent, 2);

I get an toast mentioning "My Certificate is installed". Now when I am trying to fetch it back using following code:

 try {
        KeyStore ks = KeyStore.getInstance("AndroidCAStore");
        if (ks != null) {
            ks.load(null, null);
            Enumeration aliases = ks.aliases();
            List<String> alliasesNames = Collections.list(aliases);
            for (String name : alliasesNames) {
                if (ks.getCertificate(name) instanceof X509Certificate) {
                    X509Certificate certificate = (X509Certificate) ks.getCertificate(name);
                    if (certificate.getIssuerDN().getName().contains("My Certificate")) {
                        Log.d("CERTEXIST", "**********User Cert " + certificate.getIssuerDN().getName());
                    }
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (java.security.cert.CertificateException e) {
        e.printStackTrace();
    }

I am not able to find that installed x509 in this. Also I could see the installed x509 cert in User certificate in security settings of the device.

Also when I prompt user to choose a cert for server communication using:

        KeyChain.choosePrivateKeyAlias(loginActivity, this,
            new String[]{}, null, null, -1, null);
    }

The prompt doesn't show my certificate. I am new to this certificates and key chain in Android.

I would like to know how to retrive the saved x509 cert and prompt that to user to select that certificate.

Any help is appreciated.

Upvotes: 0

Views: 2329

Answers (1)

pedrofb
pedrofb

Reputation: 39241

KeyChain.choosePrivateKeyAlias launches an antivity to prompt user to select the alias for a private key, but you have installed a certificate, not a private key, so your certificate will not be there.

KeyChain.createInstallIntent() can be used to install X509 certificates or PKCS#12 files, containing both private key and certificates. If you need to install a private key+certificate for authentication you need to provide a p12 file.

byte pkcs12Data[] = ...
installIntent.putExtra(KeyChain._PKCS12, pkcs12Data);

Upvotes: 1

Related Questions