19

I have a problem with reading certificate information. I want to read full information using java with bouncycastle library in Android programmatically. Now, i'm just using keytool command in console:

>keytool -list -keystore 1.p12 -storetype pkcs12 -v

Any suggestions?

Paul
  • 5,473
  • 1
  • 30
  • 37
ilya.stmn
  • 1,604
  • 5
  • 23
  • 41

1 Answers1

54

I've found solution, the main idea is to cast certificate to x509, then get the SubjectDN and parse values.

public class TestClass {
    public static void main(String[] args) throws Exception {

        KeyStore p12 = KeyStore.getInstance("pkcs12");
        p12.load(new FileInputStream("pkcs.p12"), "password".toCharArray());
        Enumeration<String> e = p12.aliases();
        while (e.hasMoreElements()) {
            String alias = e.nextElement();
            X509Certificate c = (X509Certificate) p12.getCertificate(alias);
            Principal subject = c.getSubjectDN();
            String subjectArray[] = subject.toString().split(",");
            for (String s : subjectArray) {
                String[] str = s.trim().split("=");
                String key = str[0];
                String value = str[1];
                System.out.println(key + " - " + value);
            }
        }
    }
}
Gozus19
  • 165
  • 19
ilya.stmn
  • 1,604
  • 5
  • 23
  • 41
  • 9
    Just remember to use java.security.* classes instead of javax.security.* – Diego Plentz Jun 20 '14 at 10:59
  • Hi @DiegoPlentz This code doesn't always work. On my machine, p12.getCertificate(alias) returns null. The pfx file was created by openssl as "openssl pkcs12 -export -out 1.pfx -in server.crt -inkey server.key". I tested your code with another pfx file, which was exported by windows certificate manager, it works fine. – Changming Sun May 09 '16 at 08:33
  • This is work fine for me but any one know how to install .p12 file on device? – Uday Nayak Jun 27 '16 at 11:11
  • @ChangmingSun Maybe try passing the "-name" option. More info: http://stackoverflow.com/questions/21138420/openssl-fails-to-produce-a-pfx-with-a-valid-alias – Vivek Chavda Oct 31 '16 at 19:49
  • @UdayNayak What do you mean "install"? The file can be generated (using openssl), as Changming has done. – Vivek Chavda Oct 31 '16 at 19:51
  • Works fine but with minor fix for NPE:`String value = (str.length > 1) ? str[1] : "";` – Alastair Dec 30 '16 at 16:19
  • 1
    a nice article with bit more details on the same.https://www.pixelstech.net/article/1420427307-Different-types-of-keystore-in-Java----PKCS12 – arvin_v_s Sep 19 '17 at 13:01