Load x509 certificate from keystore Java

We have a keystore with an imported certificate and we need to work with it in code. We are going to import cert into an X509Certificate class object. After that, you can work with it further, or simply display some information about it, for example:

  • Subject X500 Principal, Issuer X500 Principal
  • Subject DN, Issuer DN
  • Subject Alternate Names, Issuer Alternate Names
  • Subject Unique ID, Issuer Unique ID
  • Serial Number, Signature

Java code to do that:

public X509Certificate printCertInfo() throws GeneralSecurityException, IOException {
    final String type = "JKS";
    final String path = "C:/Dev/x509test/keystore.jks";
    final String password = "qwerty12345";
    KeyStore keyStore = KeyStore.getInstance(type);
    keyStore.load(new FileInputStream(path), password.toCharArray());
    X509Certificate cert = getX509FromKeystore(keyStore);
    return cert;
private X509Certificate getX509FromKeystore(KeyStore keystore) {
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        Certificate cert = keystore.getCertificate(alias);
        if (cert instanceof X509Certificate) {
            return (X509Certificate) cert;
    System.out.println("Not found!");
    return null;

If you still have any questions, feel free to ask me in the comments under this article, or write me on promark33@gmail.com.

Leave a Reply

Your email address will not be published. Required fields are marked *