用户已在SD卡上保存了.p12文件(例如他的S / MIME证书)。我想将此证书(或提取的私钥和公钥)加载到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);
将文件转换为可在密钥库中设置为证书条目的内容的最佳方法是什么?
答案 0 :(得分:3)
可以将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){}
}
答案 1 :(得分:2)
如果您想将证书安装到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);