将 .p12 文件导入 AndroidKeyStore

Import .p12-file into AndroidKeyStore

用户在 SD 卡上保存了一个 .p12 文件(例如他的 S/MIME 证书)。我想将此证书(或提取的私有密钥和 public 密钥)加载到 AndroidKeyStore 中。

File file = new File(pathToP12File);
Certificate c = null; // TODO: convert file into something I can load into the keystore

KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
ks.setCertificateEntry("myCertAlias", c);

将文件转换成可以在密钥库中设置为证书条目的最佳方法是什么?

可以将 p12 文件解释为密钥库,提取证书并将其加载到 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){}
}

如果您想将证书安装到 android KeyChain 中,您可以使用 P12 直接安装它,就像下一个方法:

    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);