
//How to export the private key from keystore?
//Does keytool not have an option to do so?
//This example use the "testkeys" file that comes with JSSE 1.0.3

import sun.misc.BASE64Encoder;
import java.security.cert.Certificate;
import java.security.*;
import java.io.File;
import java.io.FileInputStream;

class ExportPrivateKey {
 

	 public void doit(String fileName, String alias, String passPhrase) throws Exception
	 {
	
			KeyStore ks = KeyStore.getInstance("JKS");
			char[] passWord = passPhrase.toCharArray();
			BASE64Encoder myB64 = new BASE64Encoder();
			
		
			File certificateFile = new File(fileName);
			ks.load(new FileInputStream(certificateFile), passWord);
		
			KeyPair kp = getPrivateKey(ks, alias, passWord);
			PrivateKey privKey = kp.getPrivate();
			
		
			String b64 = myB64.encode(privKey.getEncoded());
		
			System.out.println("-----BEGIN PRIVATE KEY-----");
			System.out.println(b64);
			System.out.println("-----END PRIVATE KEY-----");
		
	}

//From http://javaalmanac.com/egs/java.security/GetKeyFromKs.html

	public KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) 
	{
	     try {
	         // Get private key
	         Key key = keystore.getKey(alias, password);
		         if (key instanceof PrivateKey)
		         {
		             // Get certificate of public key
		             Certificate cert = keystore.getCertificate(alias);
		 
		             // Get public key
		             PublicKey publicKey = cert.getPublicKey();
		 
		             // Return a key pair
		             return new KeyPair(publicKey, (PrivateKey)key);
		         }
		     } catch (UnrecoverableKeyException e) {
		     } catch (NoSuchAlgorithmException e) {
		     } catch (KeyStoreException e) {
		     }
	     return null;
	     
	 }
	
	public static void main(String[] args) throws Exception
	{
		if(args.length == 3 )
		{
			ExportPrivateKey myep = new ExportPrivateKey();
			myep.doit(args[0],args[1],args[2]);
		}
		else
			{System.out.println("Usage: java ExportPrivateKey keystoreFile keyAlias passphrase");}
	 }  

}
