
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.KeyGenerator;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class Gen {
	private static final String DIGITS = "0123456789abcdef";
	
    public static void main(String[] args) {
		Security.addProvider(new BouncyCastleProvider());
		Provider bc = Security.getProvider("BC");
		
		String algorithm = "RSA";
		int keysize = 1024;
		KeyPairGenerator kg = null;
		try {
			kg = KeyPairGenerator.getInstance(algorithm, bc);
			kg.initialize(keysize);
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Can't find algorithm " + algorithm);
			System.exit(-1);
		}
		
		KeyPair keyPair = kg.generateKeyPair();
		PrivateKey privateKey = keyPair.getPrivate();
		PublicKey publicKey = keyPair.getPublic();

		System.out.println(toHex(publicKey.getEncoded()));
		System.out.println(toHex(privateKey.getEncoded()));
	}
    
	public static String toHex(byte[] data) {
		return toHex(data, data.length);
	}
	
	public static String toHex(byte[] data, int length)
    {
        StringBuffer	buf = new StringBuffer();
        
        for (int i = 0; i != length; i++)
        {
            int	v = data[i] & 0xff;
            
            buf.append(DIGITS.charAt(v >> 4));
            buf.append(DIGITS.charAt(v & 0xf));
        }
        
        return buf.toString();
    }
}

@@ -1,28 +1,89 @@
+%0Aimport java.io.FileOutputStream;%0Aimport java.io.IOException;
 %0Aimport java.security.KeyPai
@@ -85,16 +85,16 @@
 eyPair;%0A
-
 import j
@@ -298,16 +298,63 @@
 curity;%0A
+import java.security.spec.PKCS8EncodedKeySpec;%0A
 import j
@@ -395,44 +395,8 @@
 ec;%0A
-%0Aimport javax.crypto.KeyGenerator;%0A%0A
 impo
@@ -1109,39 +1109,312 @@
 ();%0A%0A%09%09S
-ystem.out.println(toHex
+tring privateKeyFileName = %22private%22;%0A%09%09String publicKeyFileName = %22public%22;%0A%09%09try %7B%0A%09%09%09FileOutputStream privateKeyOutput = new FileOutputStream(privateKeyFileName);%0A%09%09%09FileOutputStream publicKeyOutput = new FileOutputStream(publicKeyFileName);%0A%09%09%09X509EncodedKeySpec X509 = new X509EncodedKeySpec
 (publicK
@@ -1433,64 +1433,270 @@
 d())
-)
 ;%0A%09%09
-System.out.println(toHex(privateKey.getEncoded()));
+%09privateKeyOutput.write(X509.getEncoded());%0A%09%09%09PKCS8EncodedKeySpec PKCS8 = new PKCS8EncodedKeySpec(privateKey.getEncoded());%0A%09%09%09publicKeyOutput.write(PKCS8.getEncoded());%0A%09%09%7D catch (IOException e) %7B%0A%09%09%09System.out.println(%22Can't write key to disk%22);%0A%09%09%7D%0A%09%09%0A%09%09
 %0A%09%7D%0A

Update Gen class Write public key and private key to disk in DER format.