Skip to content
Advertisement

Create and Import PKCS12 Certificate In Android (Java)

I am working on an Android app that handles the creation and installation of Client Certificates. I have everything set up and working except for the importing of PKCS12 Certificates into Android using the KeyChain.createInstallIntent() function. Because I need to handle the the creation of PKCS12 Certificates client side I am generating the keys and importing them into the KeyStore manually so they can be used in the PKCS12 import/export. When attempting to “export” the PKCS12 keystore and import it into the main Android KeyStore I am prompted with a “Enter Password” field. Based on the code below it should just be empty string. I’ve also tried just setting it to “something” and it still rejects any password I enter.

Assumptions that should be made for the code snippet provided:

privateKey is a PrivateKey

server.name is a String

The CA key is already installed into the main android certificate store

   void importCertificateIntoAndroid(String certStr) throws CertificateException, KeyStoreException {
        try {
            KeyStore pk12KeyStore = KeyStore.getInstance("PKCS12");
            pk12KeyStore.load(null, null);
            ByteArrayInputStream is = new ByteArrayInputStream(certStr.getBytes());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            Certificate cert = cf.generateCertificate(is);
            pk12KeyStore.setKeyEntry(server.name, privateKey, "".toCharArray(), new Certificate[]{cert});
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            pk12KeyStore.store(os, "".toCharArray());
            Intent certInstallIntent = KeyChain.createInstallIntent();
            certInstallIntent.putExtra(KeyChain.EXTRA_PKCS12, String.valueOf(os));
            certInstallIntent.putExtra(KeyChain.EXTRA_KEY_ALIAS, server.name);
            certInstallIntent.putExtra(KeyChain.EXTRA_NAME,  server.name);
            startActivity(certInstallIntent);
        } catch (Exception e) {
            Log.d(TAG, "help");
        }
    }

Advertisement

Answer

Bit too late, but the problem is in

certInstallIntent.putExtra(KeyChain.EXTRA_PKCS12, String.valueOf(os));

You have to set byte [] to this extra. Like using ‘os.toByteArray()’.

Advertisement