21
Nov

Java program to read Java Keystore

Java program to read Java Keystore:
=====================================

package browserMob_Proxy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;


public class readCertificateFileinJava {
	static InputStream is;
	public static void main(String[] args) {
		try {

	        File file = new File("C:\\Program Files\\Java\\jdk1.8.0_212\\bin\\cacerts");
	        is = new FileInputStream(file);
	        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
	        String password = "changeit";
	        keystore.load(is, password.toCharArray());


	        Enumeration<String> enumeration = keystore.aliases();
	        while(enumeration.hasMoreElements()) {
	            String alias = enumeration.nextElement();
	            System.out.println("alias name: " + alias);
	            java.security.cert.Certificate certificate = keystore.getCertificate(alias);
	            System.out.println(certificate.toString());
	            boolean isAliasPresent = keystore.containsAlias("Perfecto");
	            System.out.println("Alias present ?: "+isAliasPresent);
	        }

	    } catch (java.security.cert.CertificateException e) {
	        e.printStackTrace();
	    } catch (NoSuchAlgorithmException e) {
	        e.printStackTrace();
	    } catch (FileNotFoundException e) {
	        e.printStackTrace();
	    } catch (KeyStoreException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }finally {
	        if(null != "is")
	            try {
	                is.close();
	            } catch (IOException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }
	    }

	}

}

source: https://stackoverflow.com/questions/12893995/how-to-check-certificate-name-and-alias-in-keystore-files