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 ExportPrivateKey {
	
	public static void main( String args[] ) throws Exception {
		if(args.length!=3) {
		 System.err.println("Usage: ExportPrivateKey <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() );

		PrivateKey privateKey = (PrivateKey)store.getKey( alias, password);
		System.err.println( alias+" key found as "+privateKey.getAlgorithm()+" "+privateKey.getFormat());
		byte[] key = privateKey.getEncoded();
                System.out.write(key);
                System.out.flush();
		
	}
}

