Android - Programmatically retrieve certificate (manually installed) from keystore

Viewed 3342

On my android device, I manually installed a certificate which goal is to allow me access to a specific website.

When I look in Security -- User certs, I see can see my certificate.

My website is displayed into a webview, so I have to use the following code

@Override
public void onReceivedClientCertRequest(WebView view, final ClientCertRequest request) {
    if (mCertificates == null || mPrivateKey == null) {
        loadCertificateAndPrivateKey();
    }
    request.proceed(mPrivateKey, mCertificates);
}

In my loadCertificateAndPrivateKey() function, I am to get certificate like this

KeyStore ks = KeyStore.getInstance("AndroidCAStore");
if (ks != null)
{
    ks.load(null, null);
    Enumeration<String> aliases = ks.aliases();
    while (aliases.hasMoreElements())
    {
        String alias = (String) aliases.nextElement();
        java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) ks.getCertificate(alias);
        if(cert.getIssuerDN().getName().contains("TOTO")){
            mCertificates = new X509Certificate[1];
            mCertificates[0] = (X509Certificate)cert;


            mPrivateKey = ??;

        }
    }

But I don't know how to get the private key...
I tried this way, but key object is null (the same code works when I load my certificate directly from my app)

Key key = keyStore.getKey(alias, password.toCharArray());
if (key instanceof PrivateKey) {
    mPrivateKey = (PrivateKey)key;
}

So I have few questions :

  • Is it the correct way to retrieve the certificate ?
  • Why is it not possible to retrieve private key with the certificate's password ?
  • How to retrieve this privateKey ?

Tkanks for your answers !

1 Answers
Related