Import .p12-file into AndroidKeyStore

限于喜欢 提交于 2019-12-03 22:48:42

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

private void getCertsFromP12(String pathToFile, String passphrase){
  try {
        KeyStore p12 = KeyStore.getInstance("pkcs12");
        p12.load(new FileInputStream(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) {}
}

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

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 = new byte[bis.available()];
    bis.read(keychainP12);
    Intent installIntent = KeyChain.createInstallIntent();
    installIntent.putExtra(KeyChain.EXTRA_PKCS12, keychainP12);
    context.startActivity(installIntent);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!