Skip to content Skip to sidebar Skip to footer

Import .p12-file Into Androidkeystore

The user has saved a .p12-file (e.g. his S/MIME certificate) on SD-Card. I want to load this certificate (or the extracted private and public key) into the AndroidKeyStore. File f

Solution 1:

It's possible to interpret the p12-file as a keystore, extract the certificate and load it into the AndroidKeyStore.

privatevoidgetCertsFromP12(String pathToFile, String passphrase){
  try {
        KeyStore p12 = KeyStore.getInstance("pkcs12");
        p12.load(newFileInputStream(pathToFile), passphrase.toCharArray());
        Enumeration e = p12.aliases();
        while (e.hasMoreElements()) {
            String alias = (String) e.nextElement();
            X509Certificate c = (X509Certificate) p12.getCertificate(alias);
            addCertificateToKeyStore(c);
        }
    } catch (Exception e) {}
}

privatevoidaddCertificateToKeyStore(X509Certificate c) {
    try {
        KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);
        ks.setCertificateEntry("myCertAlias", c);
    } catch (Exception e){}
}

Solution 2:

If you want to install your certificate into the android KeyChain you can use your P12 to install it directly like in the next method:

    InputStream is = new ByteArrayInputStream(pkcs12);
    BufferedInputStream bis = new BufferedInputStream(is);
    byte[] keychainP12 = newbyte[bis.available()];
    bis.read(keychainP12);
    Intent installIntent = KeyChain.createInstallIntent();
    installIntent.putExtra(KeyChain.EXTRA_PKCS12, keychainP12);
    context.startActivity(installIntent);

Post a Comment for "Import .p12-file Into Androidkeystore"