import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.cert.*;
import java.util.*;
import java.io.*;

public class ExportPublicKey {
	
	public static void main( String args[] ) throws Exception {
		if(args.length!=3) {
		 System.err.println("Usage: ExportPublicKey <keystore> <keyalias> <password>");
		 System.err.println();
		 System.err.println("keystores *.p12 are treated as PKCS12, *.ks as JKS files");
		 System.err.println("");
 		 return;
		}
		String ksfile = args[0];
		String alias  = args[1];
	        char [] password = args[2].toCharArray();	
		String kstype = null;
                if(ksfile.substring(ksfile.length()-3).equals(".ks"))  kstype = "JKS";
                if(ksfile.substring(ksfile.length()-4).equals(".p12")) kstype = "PKCS12";
		if(kstype==null) {
		 System.err.println("keystore file name must end with .ks or .p12");
		 return;
		}

		KeyStore store = KeyStore.getInstance(kstype);
		store.load(new FileInputStream(ksfile), password);
		System.err.println( ksfile+" loaded as "+kstype+" using provider "+store.getProvider() );

		Certificate[] chain = store.getCertificateChain(alias);	
		for(int i=0;i<chain.length;i++) {
		 X509Certificate cert = (X509Certificate) chain[i];
		 System.err.println("exporting cert"+cert.toString());
		 FileOutputStream fos = new FileOutputStream(alias+"_"+i+".der");
		 fos.write(cert.getEncoded());
		 fos.flush(); fos.close();
		}
	}
}

