Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 856
CFP Avatar asked Oct 25 '25 11:10

CFP


1 Answers

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){}
}
like image 99
CFP Avatar answered Oct 28 '25 01:10

CFP