将.p12文件导入AndroidKeyStore [英] Import .p12-file into AndroidKeyStore

查看:105
本文介绍了将.p12文件导入AndroidKeyStore的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户已在SD卡上保存了一个.p12文件(例如,他的S/MIME证书).我想将此证书(或提取的私钥和公钥)加载到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 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);

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

What's the best way to convert the file into something which can be set as a certificate entry in the keystore?

推荐答案

可以将p12文件解释为密钥库,提取证书并将其加载到AndroidKeyStore中.

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){}
}

这篇关于将.p12文件导入AndroidKeyStore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆